diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubric.json b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i2-adFailure-on.json b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..67c2f752a84314f6331aea3a56fa6fb9737dfeeb --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d1-i2-adFailure-on.json @@ -0,0 +1,210 @@ +{ + "incident_time": "2026-04-19T16:32:19.033653+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "ad", + "span_kind": "SPAN_KIND_SERVER", + "span_name": "oteldemo.AdService/GetAds", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "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])", + "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.", + "onset_utc": "2026-04-19 16:40:00 UTC", + "onset_offset_seconds": 460, + "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." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(http_server_duration_milliseconds_count{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(http_server_duration_milliseconds_sum{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"adFailure\",feature_flag_result_variant=\"on\"}", + "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.", + "onset_utc": "2026-04-19 16:33:00 UTC", + "onset_offset_seconds": 40, + "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." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "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.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "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 - -", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=telescopes", + "url.path": "/api/data?contextKeys=telescopes", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "source.address": "172.18.0.28", + "server.address": "172.18.0.29:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "4a9c115c071f58e00205700b7ff2b852", + "spanId": "bf1dc411e2a87489" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-19", + "_id": "lIWapp0Br_RFnSwRY0tx", + "@timestamp": "16:37:08.414" + }, + { + "_index": "otel-logs-2026-04-19", + "_id": "yIWcpp0Br_RFnSwRvVEg", + "@timestamp": "16:39:42.669" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "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.", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "4a9c115c071f58e00205700b7ff2b852", + "spanId": "c8be6b167e3936cb" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-19", + "_id": "mIWapp0Br_RFnSwRZEt3", + "@timestamp": "16:37:08.429" + }, + { + "_index": "otel-logs-2026-04-19", + "_id": "0YWcpp0Br_RFnSwRvlE6", + "@timestamp": "16:39:42.676" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "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.", + "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.", + "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", + "smoking_gun": [ + "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", + "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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "4a9c115c071f58e00205700b7ff2b852", + "@timestamp": "16:37:08", + "user_action": "user_get_ads" + }, + { + "traceID": "bec127aafcab40a93d1d79411951afd7", + "@timestamp": "16:39:42", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.py b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.sh b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/expected.json b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0d8ae7948a11aeb5cc6854e1e9df1646504ef793 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/expected.json @@ -0,0 +1,14 @@ +{ + "events": [ + { + "event_id": "d1-i1-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-19T14:01:51.404464+00:00" + }, + { + "event_id": "d1-i2-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-19T16:32:19.033653+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i2-adFailure-on.json b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..67c2f752a84314f6331aea3a56fa6fb9737dfeeb --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d1-i2-adFailure-on.json @@ -0,0 +1,210 @@ +{ + "incident_time": "2026-04-19T16:32:19.033653+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "ad", + "span_kind": "SPAN_KIND_SERVER", + "span_name": "oteldemo.AdService/GetAds", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "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])", + "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.", + "onset_utc": "2026-04-19 16:40:00 UTC", + "onset_offset_seconds": 460, + "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." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(http_server_duration_milliseconds_count{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(http_server_duration_milliseconds_sum{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"adFailure\",feature_flag_result_variant=\"on\"}", + "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.", + "onset_utc": "2026-04-19 16:33:00 UTC", + "onset_offset_seconds": 40, + "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." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "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.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "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 - -", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=telescopes", + "url.path": "/api/data?contextKeys=telescopes", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "source.address": "172.18.0.28", + "server.address": "172.18.0.29:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "4a9c115c071f58e00205700b7ff2b852", + "spanId": "bf1dc411e2a87489" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-19", + "_id": "lIWapp0Br_RFnSwRY0tx", + "@timestamp": "16:37:08.414" + }, + { + "_index": "otel-logs-2026-04-19", + "_id": "yIWcpp0Br_RFnSwRvVEg", + "@timestamp": "16:39:42.669" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "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.", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "4a9c115c071f58e00205700b7ff2b852", + "spanId": "c8be6b167e3936cb" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-19", + "_id": "mIWapp0Br_RFnSwRZEt3", + "@timestamp": "16:37:08.429" + }, + { + "_index": "otel-logs-2026-04-19", + "_id": "0YWcpp0Br_RFnSwRvlE6", + "@timestamp": "16:39:42.676" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "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.", + "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.", + "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", + "smoking_gun": [ + "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", + "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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "4a9c115c071f58e00205700b7ff2b852", + "@timestamp": "16:37:08", + "user_action": "user_get_ads" + }, + { + "traceID": "bec127aafcab40a93d1d79411951afd7", + "@timestamp": "16:39:42", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/test.sh b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d1-c1-admanualgc-on-univ00-universal_ttd15m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/Dockerfile b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/docker-compose.yaml b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/check_prediction.py b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubric.json b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.py b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.sh b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/check_prediction.py b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/expected.json b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d160701780e01274795961982abcc76d34525d37 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d1-i1-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-19T14:01:51.404464+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/test.sh b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d160701780e01274795961982abcc76d34525d37 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d1-i1-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-19T14:01:51.404464+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubric.json b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.py b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.sh b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/expected.json b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d160701780e01274795961982abcc76d34525d37 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d1-i1-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-19T14:01:51.404464+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/test.sh b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d1-i1-imageslowload-on-univ00-universal_ttd60m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/rubric.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/solve.py b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/solve.sh b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/expected.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d160701780e01274795961982abcc76d34525d37 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d1-i1-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-19T14:01:51.404464+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/test.sh b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-00-hard_ttd480m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/environment/Dockerfile b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/environment/docker-compose.yaml b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/check_prediction.py b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubric.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d1-i2-adFailure-on.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d1-i2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..67c2f752a84314f6331aea3a56fa6fb9737dfeeb --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d1-i2-adFailure-on.json @@ -0,0 +1,210 @@ +{ + "incident_time": "2026-04-19T16:32:19.033653+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "ad", + "span_kind": "SPAN_KIND_SERVER", + "span_name": "oteldemo.AdService/GetAds", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "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])", + "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.", + "onset_utc": "2026-04-19 16:40:00 UTC", + "onset_offset_seconds": 460, + "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." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(http_server_duration_milliseconds_count{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(http_server_duration_milliseconds_sum{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"adFailure\",feature_flag_result_variant=\"on\"}", + "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.", + "onset_utc": "2026-04-19 16:33:00 UTC", + "onset_offset_seconds": 40, + "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." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "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.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "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 - -", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=telescopes", + "url.path": "/api/data?contextKeys=telescopes", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "source.address": "172.18.0.28", + "server.address": "172.18.0.29:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "4a9c115c071f58e00205700b7ff2b852", + "spanId": "bf1dc411e2a87489" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-19", + "_id": "lIWapp0Br_RFnSwRY0tx", + "@timestamp": "16:37:08.414" + }, + { + "_index": "otel-logs-2026-04-19", + "_id": "yIWcpp0Br_RFnSwRvVEg", + "@timestamp": "16:39:42.669" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "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.", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "4a9c115c071f58e00205700b7ff2b852", + "spanId": "c8be6b167e3936cb" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-19", + "_id": "mIWapp0Br_RFnSwRZEt3", + "@timestamp": "16:37:08.429" + }, + { + "_index": "otel-logs-2026-04-19", + "_id": "0YWcpp0Br_RFnSwRvlE6", + "@timestamp": "16:39:42.676" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "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.", + "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.", + "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", + "smoking_gun": [ + "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", + "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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "4a9c115c071f58e00205700b7ff2b852", + "@timestamp": "16:37:08", + "user_action": "user_get_ads" + }, + { + "traceID": "bec127aafcab40a93d1d79411951afd7", + "@timestamp": "16:39:42", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/solve.py b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/solve.sh b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/check_prediction.py b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/expected.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0d8ae7948a11aeb5cc6854e1e9df1646504ef793 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/expected.json @@ -0,0 +1,14 @@ +{ + "events": [ + { + "event_id": "d1-i1-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-19T14:01:51.404464+00:00" + }, + { + "event_id": "d1-i2-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-19T16:32:19.033653+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..667ec8adb974ee69207390d21b1931667df6e783 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d1-i1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-19T14:01:51.404464+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d1-i2-adFailure-on.json b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d1-i2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..67c2f752a84314f6331aea3a56fa6fb9737dfeeb --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d1-i2-adFailure-on.json @@ -0,0 +1,210 @@ +{ + "incident_time": "2026-04-19T16:32:19.033653+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\",service_name=\"ad\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "ad", + "span_kind": "SPAN_KIND_SERVER", + "span_name": "oteldemo.AdService/GetAds", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "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])", + "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.", + "onset_utc": "2026-04-19 16:40:00 UTC", + "onset_offset_seconds": 460, + "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." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(http_server_duration_milliseconds_count{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(http_server_duration_milliseconds_sum{http_status_code=\"500\",service_name=\"frontend\",http_method=\"GET\"}[5m])", + "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.", + "onset_utc": "2026-04-19 16:41:00 UTC", + "onset_offset_seconds": 520, + "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." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"adFailure\",feature_flag_result_variant=\"on\"}", + "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.", + "onset_utc": "2026-04-19 16:33:00 UTC", + "onset_offset_seconds": 40, + "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." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "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.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "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 - -", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=telescopes", + "url.path": "/api/data?contextKeys=telescopes", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "source.address": "172.18.0.28", + "server.address": "172.18.0.29:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "4a9c115c071f58e00205700b7ff2b852", + "spanId": "bf1dc411e2a87489" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-19", + "_id": "lIWapp0Br_RFnSwRY0tx", + "@timestamp": "16:37:08.414" + }, + { + "_index": "otel-logs-2026-04-19", + "_id": "yIWcpp0Br_RFnSwRvVEg", + "@timestamp": "16:39:42.669" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "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.", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "4a9c115c071f58e00205700b7ff2b852", + "spanId": "c8be6b167e3936cb" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-19", + "_id": "mIWapp0Br_RFnSwRZEt3", + "@timestamp": "16:37:08.429" + }, + { + "_index": "otel-logs-2026-04-19", + "_id": "0YWcpp0Br_RFnSwRvlE6", + "@timestamp": "16:39:42.676" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "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.", + "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.", + "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", + "smoking_gun": [ + "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", + "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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "4a9c115c071f58e00205700b7ff2b852", + "@timestamp": "16:37:08", + "user_action": "user_get_ads" + }, + { + "traceID": "bec127aafcab40a93d1d79411951afd7", + "@timestamp": "16:39:42", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/test.sh b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d1-n1-loadgeneratorfloodhomepage-on-univ00-universal_ttd480m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/environment/Dockerfile b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/environment/docker-compose.yaml b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/check_prediction.py b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/solve.py b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/solve.sh b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/check_prediction.py b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/expected.json b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/test.sh b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-cc1-adfailure-on-univ00-universal_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/environment/Dockerfile b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/environment/docker-compose.yaml b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/check_prediction.py b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/rubric.json b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/rubric.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/rubrics/d2-cc1-adFailure-on.json b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/rubrics/d2-cc1-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/rubrics/d2-cc1-adFailure-on.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/solve.py b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/solve.sh b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/check_prediction.py b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/expected.json b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8d5c83908a65a883738532f552d3e31b2043566d --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d2-cc1-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-20T15:08:20.478349+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/rubrics/d2-cc1-adFailure-on.json b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/rubrics/d2-cc1-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/rubrics/d2-cc1-adFailure-on.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/test.sh b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-01-hard_ttd480m_period_previous-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/environment/Dockerfile b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/environment/docker-compose.yaml b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/check_prediction.py b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/solve.py b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/solve.sh b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/check_prediction.py b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/expected.json b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/test.sh b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-03-easy_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/environment/Dockerfile b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/environment/docker-compose.yaml b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/check_prediction.py b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/solve.py b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/solve.sh b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/check_prediction.py b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/expected.json b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/test.sh b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-cc1-admanualgc-on-univ00-universal_control_post60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/environment/Dockerfile b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/environment/docker-compose.yaml b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/check_prediction.py b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubric.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..9454f12c8c88a1ce7f4ac37f086596f4100ddc0e --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubric.json @@ -0,0 +1,427 @@ +{ + "incident_time": "2026-04-20T21:09:45.917730+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container CPU utilization spiked ~3x (avg 0.17 to 0.51) due to ConnectionMultiplexer.Connect exponential-backoff retry loops against the unreachable badhost:1234 host", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline fluctuates roughly 0.06–0.09 with occasional spikes to ~0.2. After the incident at 21:10, the value at 21:11 (0.135) begins a sustained rise, with subsequent values consistently elevated (0.26, 0.36, 0.25, 0.37, 1.09, etc.), well above the pre-incident baseline. 21:11 is the first post-incident timestamp showing a clear upward departure that persists." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"cart\"}", + "description": "Cart container memory usage jumped from stable ~53MB to avg ~65MB (peak 71MB, +22%) due to accumulating connection objects and retry state from repeated failed connection attempts to badhost:1234", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline is ~53-54 MB. At 21:11 the value jumps to ~56.1 MB, a clear departure from baseline, and continues rising to ~67 MB. This is the first timestamp after the incident time showing a significant spike above the stable pre-incident level." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"EmptyCart\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "gRPC client-side count of successful (code 0) EmptyCart calls from checkout to cart service. Collapsed from ~0.020/s to zero after cartFailure was enabled, because all EmptyCart calls now route to _badCartStore and fail.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows regular activity around 0.017-0.033 req/s. At 20:58 the last typical value (0.0166667) appears, then the signal drops to zero at 20:59 and stays near zero or at drastically reduced levels (~0.004) through the incident time and beyond, never recovering to the pre-incident pattern. This is the last timestamp where the pre-incident active pattern is still present." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(kafka_consumer_bytes_consumed_total{topic=\"orders\"}[5m])", + "description": "Rate of bytes consumed by the fraud-detection Kafka consumer from the 'orders' topic. Dropped ~45% for the same reason: fewer order messages are published to Kafka due to blocked checkout RPCs.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows active oscillating values around 4-6 bytes/s. At 20:58 the value drops to 3.525, then goes to 0 at 20:59 and stays at 0 through 21:04. The signal partially recovers at ~1-2.5 after that but never returns to the pre-incident 4-6 range. The last timestamp showing the active pre-incident pattern is 20:58, marking the onset of the collapse." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for cartFailure flag evaluating to variant 'on'. Was zero before; spiked to ~0.020/s after the flag was flipped on at 21:09:45 UTC.", + "onset_utc": "2026-04-20 21:12:00 UTC", + "onset_offset_seconds": 134, + "onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 21:12:00 UTC, roughly 2 minutes after the incident time of 21:09:45 UTC, which is consistent with the 5m rate window needing time to populate. This first appearance is the onset." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 21:10:16.891 and 21:18:32.951 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T21:10:16.891Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 388 24 15000 - \"-\" \"python-requests/2.32.5\" \"51a1c50a-aae4-9f34-a007-bc1cc79bd191\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:51780 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "Zp-7rJ0Br_RFnSwRCHb6", + "@timestamp": "21:10:16.891" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "UZ-7rJ0Br_RFnSwRu3in", + "@timestamp": "21:11:02.555" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ-7rJ0Br_RFnSwR93lV", + "@timestamp": "21:11:17.818" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5-7rJ0Br_RFnSwR_nkN", + "@timestamp": "21:11:19.277" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1Z-9rJ0Br_RFnSwR2329", + "@timestamp": "21:13:21.589" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "k5--rJ0Br_RFnSwRaH9q", + "@timestamp": "21:13:57.485" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "oJ--rJ0Br_RFnSwRyYAN", + "@timestamp": "21:14:22.110" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "c5-_rJ0Br_RFnSwRn4Pu", + "@timestamp": "21:15:17.506" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "n5_ArJ0Br_RFnSwRTIXp", + "@timestamp": "21:16:01.367" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "HZ_ArJ0Br_RFnSwRqYed", + "@timestamp": "21:16:25.280" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8Z_BrJ0Br_RFnSwRB4dg", + "@timestamp": "21:16:48.941" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ_BrJ0Br_RFnSwRVomV", + "@timestamp": "21:17:09.292" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5_CrJ0Br_RFnSwRJIue", + "@timestamp": "21:18:01.900" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_p_CrJ0Br_RFnSwRVIuL", + "@timestamp": "21:18:14.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Np_CrJ0Br_RFnSwRnY3B", + "@timestamp": "21:18:32.951" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 21:12:36.954 and 21:18:39.671 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "6p-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.954" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Cp--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.969" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "-5_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.671" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 21:12:36.994 and 21:18:39.672 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 40 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "65-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.994" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.970" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IZ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_J_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.672" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 21:10:16 and 21:18:32 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 140–1327 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 140 s and 1327 s across the 15 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "da81017ad4d80fa404b38e5e686886ed", + "@timestamp": "21:18:32", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1327.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "01dbf1eeb70a6f0207d8192cb85e7087", + "@timestamp": "21:18:14", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1224.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d35e675f70f607cbc7f535ce11990750", + "@timestamp": "21:18:01", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1125.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "8ccd4dad719adb45b128029d18f7cb64", + "@timestamp": "21:17:09", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1054.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "449da5463a4da2f53b3e0ab20560d1a6", + "@timestamp": "21:16:48", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "957.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cecc13a9b88bc0a3114e66c0f68286d", + "@timestamp": "21:16:25", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "848.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "12779fc1e046d382708fe0c29e909448", + "@timestamp": "21:16:01", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "756.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "bd7e236996ccb389179dbeff40dc3961", + "@timestamp": "21:15:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "688.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "6ccda48d54e9cd419cbcb4114b3f7f88", + "@timestamp": "21:14:22", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "624.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "7cc56e148ec42ca034321003b04f6361", + "@timestamp": "21:13:57", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "523.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "40ff8f925cd9b5b67c14a11a4cbf8ff9", + "@timestamp": "21:13:21", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "443.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d550968745fedca02a94c025efa59de8", + "@timestamp": "21:11:19", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "440.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0219b564d1854c435e5db02ecff24a69", + "@timestamp": "21:11:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "319.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1f2b90a2166a087db5a7d18072a042cf", + "@timestamp": "21:11:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "219.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cc6277fa9093cda3b77af2ecb275bb6", + "@timestamp": "21:10:16", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "140.1", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-cartFailure-on.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..9454f12c8c88a1ce7f4ac37f086596f4100ddc0e --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-cartFailure-on.json @@ -0,0 +1,427 @@ +{ + "incident_time": "2026-04-20T21:09:45.917730+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container CPU utilization spiked ~3x (avg 0.17 to 0.51) due to ConnectionMultiplexer.Connect exponential-backoff retry loops against the unreachable badhost:1234 host", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline fluctuates roughly 0.06–0.09 with occasional spikes to ~0.2. After the incident at 21:10, the value at 21:11 (0.135) begins a sustained rise, with subsequent values consistently elevated (0.26, 0.36, 0.25, 0.37, 1.09, etc.), well above the pre-incident baseline. 21:11 is the first post-incident timestamp showing a clear upward departure that persists." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"cart\"}", + "description": "Cart container memory usage jumped from stable ~53MB to avg ~65MB (peak 71MB, +22%) due to accumulating connection objects and retry state from repeated failed connection attempts to badhost:1234", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline is ~53-54 MB. At 21:11 the value jumps to ~56.1 MB, a clear departure from baseline, and continues rising to ~67 MB. This is the first timestamp after the incident time showing a significant spike above the stable pre-incident level." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"EmptyCart\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "gRPC client-side count of successful (code 0) EmptyCart calls from checkout to cart service. Collapsed from ~0.020/s to zero after cartFailure was enabled, because all EmptyCart calls now route to _badCartStore and fail.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows regular activity around 0.017-0.033 req/s. At 20:58 the last typical value (0.0166667) appears, then the signal drops to zero at 20:59 and stays near zero or at drastically reduced levels (~0.004) through the incident time and beyond, never recovering to the pre-incident pattern. This is the last timestamp where the pre-incident active pattern is still present." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(kafka_consumer_bytes_consumed_total{topic=\"orders\"}[5m])", + "description": "Rate of bytes consumed by the fraud-detection Kafka consumer from the 'orders' topic. Dropped ~45% for the same reason: fewer order messages are published to Kafka due to blocked checkout RPCs.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows active oscillating values around 4-6 bytes/s. At 20:58 the value drops to 3.525, then goes to 0 at 20:59 and stays at 0 through 21:04. The signal partially recovers at ~1-2.5 after that but never returns to the pre-incident 4-6 range. The last timestamp showing the active pre-incident pattern is 20:58, marking the onset of the collapse." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for cartFailure flag evaluating to variant 'on'. Was zero before; spiked to ~0.020/s after the flag was flipped on at 21:09:45 UTC.", + "onset_utc": "2026-04-20 21:12:00 UTC", + "onset_offset_seconds": 134, + "onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 21:12:00 UTC, roughly 2 minutes after the incident time of 21:09:45 UTC, which is consistent with the 5m rate window needing time to populate. This first appearance is the onset." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 21:10:16.891 and 21:18:32.951 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T21:10:16.891Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 388 24 15000 - \"-\" \"python-requests/2.32.5\" \"51a1c50a-aae4-9f34-a007-bc1cc79bd191\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:51780 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "Zp-7rJ0Br_RFnSwRCHb6", + "@timestamp": "21:10:16.891" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "UZ-7rJ0Br_RFnSwRu3in", + "@timestamp": "21:11:02.555" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ-7rJ0Br_RFnSwR93lV", + "@timestamp": "21:11:17.818" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5-7rJ0Br_RFnSwR_nkN", + "@timestamp": "21:11:19.277" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1Z-9rJ0Br_RFnSwR2329", + "@timestamp": "21:13:21.589" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "k5--rJ0Br_RFnSwRaH9q", + "@timestamp": "21:13:57.485" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "oJ--rJ0Br_RFnSwRyYAN", + "@timestamp": "21:14:22.110" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "c5-_rJ0Br_RFnSwRn4Pu", + "@timestamp": "21:15:17.506" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "n5_ArJ0Br_RFnSwRTIXp", + "@timestamp": "21:16:01.367" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "HZ_ArJ0Br_RFnSwRqYed", + "@timestamp": "21:16:25.280" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8Z_BrJ0Br_RFnSwRB4dg", + "@timestamp": "21:16:48.941" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ_BrJ0Br_RFnSwRVomV", + "@timestamp": "21:17:09.292" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5_CrJ0Br_RFnSwRJIue", + "@timestamp": "21:18:01.900" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_p_CrJ0Br_RFnSwRVIuL", + "@timestamp": "21:18:14.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Np_CrJ0Br_RFnSwRnY3B", + "@timestamp": "21:18:32.951" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 21:12:36.954 and 21:18:39.671 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "6p-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.954" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Cp--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.969" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "-5_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.671" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 21:12:36.994 and 21:18:39.672 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 40 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "65-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.994" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.970" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IZ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_J_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.672" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 21:10:16 and 21:18:32 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 140–1327 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 140 s and 1327 s across the 15 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "da81017ad4d80fa404b38e5e686886ed", + "@timestamp": "21:18:32", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1327.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "01dbf1eeb70a6f0207d8192cb85e7087", + "@timestamp": "21:18:14", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1224.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d35e675f70f607cbc7f535ce11990750", + "@timestamp": "21:18:01", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1125.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "8ccd4dad719adb45b128029d18f7cb64", + "@timestamp": "21:17:09", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1054.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "449da5463a4da2f53b3e0ab20560d1a6", + "@timestamp": "21:16:48", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "957.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cecc13a9b88bc0a3114e66c0f68286d", + "@timestamp": "21:16:25", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "848.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "12779fc1e046d382708fe0c29e909448", + "@timestamp": "21:16:01", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "756.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "bd7e236996ccb389179dbeff40dc3961", + "@timestamp": "21:15:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "688.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "6ccda48d54e9cd419cbcb4114b3f7f88", + "@timestamp": "21:14:22", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "624.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "7cc56e148ec42ca034321003b04f6361", + "@timestamp": "21:13:57", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "523.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "40ff8f925cd9b5b67c14a11a4cbf8ff9", + "@timestamp": "21:13:21", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "443.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d550968745fedca02a94c025efa59de8", + "@timestamp": "21:11:19", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "440.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0219b564d1854c435e5db02ecff24a69", + "@timestamp": "21:11:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "319.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1f2b90a2166a087db5a7d18072a042cf", + "@timestamp": "21:11:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "219.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cc6277fa9093cda3b77af2ecb275bb6", + "@timestamp": "21:10:16", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "140.1", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-50%.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-50%.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/solve.py b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/solve.sh b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/check_prediction.py b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/expected.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..046b9fd763014a3175d8a0043f551188a5df390c --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-20T21:09:45.917730+00:00" + }, + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + }, + { + "event_id": "d2-d1dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:09:32.298358+00:00" + }, + { + "event_id": "d2-d1dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:39:39.920177+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-cartFailure-on.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..9454f12c8c88a1ce7f4ac37f086596f4100ddc0e --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-cartFailure-on.json @@ -0,0 +1,427 @@ +{ + "incident_time": "2026-04-20T21:09:45.917730+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container CPU utilization spiked ~3x (avg 0.17 to 0.51) due to ConnectionMultiplexer.Connect exponential-backoff retry loops against the unreachable badhost:1234 host", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline fluctuates roughly 0.06–0.09 with occasional spikes to ~0.2. After the incident at 21:10, the value at 21:11 (0.135) begins a sustained rise, with subsequent values consistently elevated (0.26, 0.36, 0.25, 0.37, 1.09, etc.), well above the pre-incident baseline. 21:11 is the first post-incident timestamp showing a clear upward departure that persists." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"cart\"}", + "description": "Cart container memory usage jumped from stable ~53MB to avg ~65MB (peak 71MB, +22%) due to accumulating connection objects and retry state from repeated failed connection attempts to badhost:1234", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline is ~53-54 MB. At 21:11 the value jumps to ~56.1 MB, a clear departure from baseline, and continues rising to ~67 MB. This is the first timestamp after the incident time showing a significant spike above the stable pre-incident level." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"EmptyCart\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "gRPC client-side count of successful (code 0) EmptyCart calls from checkout to cart service. Collapsed from ~0.020/s to zero after cartFailure was enabled, because all EmptyCart calls now route to _badCartStore and fail.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows regular activity around 0.017-0.033 req/s. At 20:58 the last typical value (0.0166667) appears, then the signal drops to zero at 20:59 and stays near zero or at drastically reduced levels (~0.004) through the incident time and beyond, never recovering to the pre-incident pattern. This is the last timestamp where the pre-incident active pattern is still present." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(kafka_consumer_bytes_consumed_total{topic=\"orders\"}[5m])", + "description": "Rate of bytes consumed by the fraud-detection Kafka consumer from the 'orders' topic. Dropped ~45% for the same reason: fewer order messages are published to Kafka due to blocked checkout RPCs.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows active oscillating values around 4-6 bytes/s. At 20:58 the value drops to 3.525, then goes to 0 at 20:59 and stays at 0 through 21:04. The signal partially recovers at ~1-2.5 after that but never returns to the pre-incident 4-6 range. The last timestamp showing the active pre-incident pattern is 20:58, marking the onset of the collapse." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for cartFailure flag evaluating to variant 'on'. Was zero before; spiked to ~0.020/s after the flag was flipped on at 21:09:45 UTC.", + "onset_utc": "2026-04-20 21:12:00 UTC", + "onset_offset_seconds": 134, + "onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 21:12:00 UTC, roughly 2 minutes after the incident time of 21:09:45 UTC, which is consistent with the 5m rate window needing time to populate. This first appearance is the onset." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 21:10:16.891 and 21:18:32.951 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T21:10:16.891Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 388 24 15000 - \"-\" \"python-requests/2.32.5\" \"51a1c50a-aae4-9f34-a007-bc1cc79bd191\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:51780 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "Zp-7rJ0Br_RFnSwRCHb6", + "@timestamp": "21:10:16.891" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "UZ-7rJ0Br_RFnSwRu3in", + "@timestamp": "21:11:02.555" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ-7rJ0Br_RFnSwR93lV", + "@timestamp": "21:11:17.818" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5-7rJ0Br_RFnSwR_nkN", + "@timestamp": "21:11:19.277" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1Z-9rJ0Br_RFnSwR2329", + "@timestamp": "21:13:21.589" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "k5--rJ0Br_RFnSwRaH9q", + "@timestamp": "21:13:57.485" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "oJ--rJ0Br_RFnSwRyYAN", + "@timestamp": "21:14:22.110" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "c5-_rJ0Br_RFnSwRn4Pu", + "@timestamp": "21:15:17.506" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "n5_ArJ0Br_RFnSwRTIXp", + "@timestamp": "21:16:01.367" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "HZ_ArJ0Br_RFnSwRqYed", + "@timestamp": "21:16:25.280" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8Z_BrJ0Br_RFnSwRB4dg", + "@timestamp": "21:16:48.941" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ_BrJ0Br_RFnSwRVomV", + "@timestamp": "21:17:09.292" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5_CrJ0Br_RFnSwRJIue", + "@timestamp": "21:18:01.900" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_p_CrJ0Br_RFnSwRVIuL", + "@timestamp": "21:18:14.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Np_CrJ0Br_RFnSwRnY3B", + "@timestamp": "21:18:32.951" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 21:12:36.954 and 21:18:39.671 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "6p-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.954" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Cp--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.969" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "-5_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.671" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 21:12:36.994 and 21:18:39.672 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 40 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "65-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.994" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.970" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IZ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_J_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.672" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 21:10:16 and 21:18:32 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 140–1327 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 140 s and 1327 s across the 15 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "da81017ad4d80fa404b38e5e686886ed", + "@timestamp": "21:18:32", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1327.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "01dbf1eeb70a6f0207d8192cb85e7087", + "@timestamp": "21:18:14", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1224.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d35e675f70f607cbc7f535ce11990750", + "@timestamp": "21:18:01", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1125.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "8ccd4dad719adb45b128029d18f7cb64", + "@timestamp": "21:17:09", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1054.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "449da5463a4da2f53b3e0ab20560d1a6", + "@timestamp": "21:16:48", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "957.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cecc13a9b88bc0a3114e66c0f68286d", + "@timestamp": "21:16:25", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "848.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "12779fc1e046d382708fe0c29e909448", + "@timestamp": "21:16:01", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "756.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "bd7e236996ccb389179dbeff40dc3961", + "@timestamp": "21:15:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "688.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "6ccda48d54e9cd419cbcb4114b3f7f88", + "@timestamp": "21:14:22", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "624.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "7cc56e148ec42ca034321003b04f6361", + "@timestamp": "21:13:57", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "523.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "40ff8f925cd9b5b67c14a11a4cbf8ff9", + "@timestamp": "21:13:21", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "443.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d550968745fedca02a94c025efa59de8", + "@timestamp": "21:11:19", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "440.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0219b564d1854c435e5db02ecff24a69", + "@timestamp": "21:11:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "319.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1f2b90a2166a087db5a7d18072a042cf", + "@timestamp": "21:11:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "219.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cc6277fa9093cda3b77af2ecb275bb6", + "@timestamp": "21:10:16", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "140.1", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-50%.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-50%.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/test.sh b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-cartfailure-on-00-hard_ttd480m_period_same-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-paymentFailure-50%.json b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-paymentFailure-50%.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..1ff6deca5a10ece79b368da4b08a3b57356a694c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:09:32.298358+00:00" + }, + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + }, + { + "event_id": "d2-d1dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:39:39.920177+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-paymentFailure-50%.json b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-paymentFailure-50%.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-00-hard_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubric.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubric.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-cc1-adFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-cc1-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-cc1-adFailure-on.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/solve.py b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/solve.sh b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/expected.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..07a1ac4024a9e29dad673d4d9373e85353603be3 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:09:32.298358+00:00" + }, + { + "event_id": "d2-cc1-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-20T15:08:20.478349+00:00" + }, + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-cc1-adFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-cc1-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-cc1-adFailure-on.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/test.sh b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd15m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/environment/Dockerfile b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubric.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubric.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-cc1-adFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-cc1-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-cc1-adFailure-on.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-cartFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..9454f12c8c88a1ce7f4ac37f086596f4100ddc0e --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-cartFailure-on.json @@ -0,0 +1,427 @@ +{ + "incident_time": "2026-04-20T21:09:45.917730+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container CPU utilization spiked ~3x (avg 0.17 to 0.51) due to ConnectionMultiplexer.Connect exponential-backoff retry loops against the unreachable badhost:1234 host", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline fluctuates roughly 0.06–0.09 with occasional spikes to ~0.2. After the incident at 21:10, the value at 21:11 (0.135) begins a sustained rise, with subsequent values consistently elevated (0.26, 0.36, 0.25, 0.37, 1.09, etc.), well above the pre-incident baseline. 21:11 is the first post-incident timestamp showing a clear upward departure that persists." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"cart\"}", + "description": "Cart container memory usage jumped from stable ~53MB to avg ~65MB (peak 71MB, +22%) due to accumulating connection objects and retry state from repeated failed connection attempts to badhost:1234", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline is ~53-54 MB. At 21:11 the value jumps to ~56.1 MB, a clear departure from baseline, and continues rising to ~67 MB. This is the first timestamp after the incident time showing a significant spike above the stable pre-incident level." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"EmptyCart\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "gRPC client-side count of successful (code 0) EmptyCart calls from checkout to cart service. Collapsed from ~0.020/s to zero after cartFailure was enabled, because all EmptyCart calls now route to _badCartStore and fail.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows regular activity around 0.017-0.033 req/s. At 20:58 the last typical value (0.0166667) appears, then the signal drops to zero at 20:59 and stays near zero or at drastically reduced levels (~0.004) through the incident time and beyond, never recovering to the pre-incident pattern. This is the last timestamp where the pre-incident active pattern is still present." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(kafka_consumer_bytes_consumed_total{topic=\"orders\"}[5m])", + "description": "Rate of bytes consumed by the fraud-detection Kafka consumer from the 'orders' topic. Dropped ~45% for the same reason: fewer order messages are published to Kafka due to blocked checkout RPCs.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows active oscillating values around 4-6 bytes/s. At 20:58 the value drops to 3.525, then goes to 0 at 20:59 and stays at 0 through 21:04. The signal partially recovers at ~1-2.5 after that but never returns to the pre-incident 4-6 range. The last timestamp showing the active pre-incident pattern is 20:58, marking the onset of the collapse." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for cartFailure flag evaluating to variant 'on'. Was zero before; spiked to ~0.020/s after the flag was flipped on at 21:09:45 UTC.", + "onset_utc": "2026-04-20 21:12:00 UTC", + "onset_offset_seconds": 134, + "onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 21:12:00 UTC, roughly 2 minutes after the incident time of 21:09:45 UTC, which is consistent with the 5m rate window needing time to populate. This first appearance is the onset." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 21:10:16.891 and 21:18:32.951 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T21:10:16.891Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 388 24 15000 - \"-\" \"python-requests/2.32.5\" \"51a1c50a-aae4-9f34-a007-bc1cc79bd191\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:51780 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "Zp-7rJ0Br_RFnSwRCHb6", + "@timestamp": "21:10:16.891" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "UZ-7rJ0Br_RFnSwRu3in", + "@timestamp": "21:11:02.555" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ-7rJ0Br_RFnSwR93lV", + "@timestamp": "21:11:17.818" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5-7rJ0Br_RFnSwR_nkN", + "@timestamp": "21:11:19.277" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1Z-9rJ0Br_RFnSwR2329", + "@timestamp": "21:13:21.589" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "k5--rJ0Br_RFnSwRaH9q", + "@timestamp": "21:13:57.485" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "oJ--rJ0Br_RFnSwRyYAN", + "@timestamp": "21:14:22.110" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "c5-_rJ0Br_RFnSwRn4Pu", + "@timestamp": "21:15:17.506" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "n5_ArJ0Br_RFnSwRTIXp", + "@timestamp": "21:16:01.367" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "HZ_ArJ0Br_RFnSwRqYed", + "@timestamp": "21:16:25.280" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8Z_BrJ0Br_RFnSwRB4dg", + "@timestamp": "21:16:48.941" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ_BrJ0Br_RFnSwRVomV", + "@timestamp": "21:17:09.292" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5_CrJ0Br_RFnSwRJIue", + "@timestamp": "21:18:01.900" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_p_CrJ0Br_RFnSwRVIuL", + "@timestamp": "21:18:14.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Np_CrJ0Br_RFnSwRnY3B", + "@timestamp": "21:18:32.951" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 21:12:36.954 and 21:18:39.671 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "6p-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.954" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Cp--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.969" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "-5_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.671" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 21:12:36.994 and 21:18:39.672 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 40 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "65-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.994" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.970" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IZ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_J_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.672" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 21:10:16 and 21:18:32 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 140–1327 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 140 s and 1327 s across the 15 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "da81017ad4d80fa404b38e5e686886ed", + "@timestamp": "21:18:32", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1327.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "01dbf1eeb70a6f0207d8192cb85e7087", + "@timestamp": "21:18:14", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1224.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d35e675f70f607cbc7f535ce11990750", + "@timestamp": "21:18:01", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1125.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "8ccd4dad719adb45b128029d18f7cb64", + "@timestamp": "21:17:09", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1054.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "449da5463a4da2f53b3e0ab20560d1a6", + "@timestamp": "21:16:48", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "957.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cecc13a9b88bc0a3114e66c0f68286d", + "@timestamp": "21:16:25", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "848.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "12779fc1e046d382708fe0c29e909448", + "@timestamp": "21:16:01", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "756.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "bd7e236996ccb389179dbeff40dc3961", + "@timestamp": "21:15:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "688.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "6ccda48d54e9cd419cbcb4114b3f7f88", + "@timestamp": "21:14:22", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "624.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "7cc56e148ec42ca034321003b04f6361", + "@timestamp": "21:13:57", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "523.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "40ff8f925cd9b5b67c14a11a4cbf8ff9", + "@timestamp": "21:13:21", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "443.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d550968745fedca02a94c025efa59de8", + "@timestamp": "21:11:19", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "440.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0219b564d1854c435e5db02ecff24a69", + "@timestamp": "21:11:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "319.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1f2b90a2166a087db5a7d18072a042cf", + "@timestamp": "21:11:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "219.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cc6277fa9093cda3b77af2ecb275bb6", + "@timestamp": "21:10:16", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "140.1", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-50%.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-paymentFailure-50%.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/solve.py b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/solve.sh b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/expected.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..288c375b0061eefcfb7a809d73b15e96516582a3 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/expected.json @@ -0,0 +1,29 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:09:32.298358+00:00" + }, + { + "event_id": "d2-cc1-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-20T15:08:20.478349+00:00" + }, + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + }, + { + "event_id": "d2-d1dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:39:39.920177+00:00" + }, + { + "event_id": "d2-d1dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-20T21:09:45.917730+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-cc1-adFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-cc1-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-cc1-adFailure-on.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-cartFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..9454f12c8c88a1ce7f4ac37f086596f4100ddc0e --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-cartFailure-on.json @@ -0,0 +1,427 @@ +{ + "incident_time": "2026-04-20T21:09:45.917730+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container CPU utilization spiked ~3x (avg 0.17 to 0.51) due to ConnectionMultiplexer.Connect exponential-backoff retry loops against the unreachable badhost:1234 host", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline fluctuates roughly 0.06–0.09 with occasional spikes to ~0.2. After the incident at 21:10, the value at 21:11 (0.135) begins a sustained rise, with subsequent values consistently elevated (0.26, 0.36, 0.25, 0.37, 1.09, etc.), well above the pre-incident baseline. 21:11 is the first post-incident timestamp showing a clear upward departure that persists." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"cart\"}", + "description": "Cart container memory usage jumped from stable ~53MB to avg ~65MB (peak 71MB, +22%) due to accumulating connection objects and retry state from repeated failed connection attempts to badhost:1234", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline is ~53-54 MB. At 21:11 the value jumps to ~56.1 MB, a clear departure from baseline, and continues rising to ~67 MB. This is the first timestamp after the incident time showing a significant spike above the stable pre-incident level." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"EmptyCart\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "gRPC client-side count of successful (code 0) EmptyCart calls from checkout to cart service. Collapsed from ~0.020/s to zero after cartFailure was enabled, because all EmptyCart calls now route to _badCartStore and fail.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows regular activity around 0.017-0.033 req/s. At 20:58 the last typical value (0.0166667) appears, then the signal drops to zero at 20:59 and stays near zero or at drastically reduced levels (~0.004) through the incident time and beyond, never recovering to the pre-incident pattern. This is the last timestamp where the pre-incident active pattern is still present." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(kafka_consumer_bytes_consumed_total{topic=\"orders\"}[5m])", + "description": "Rate of bytes consumed by the fraud-detection Kafka consumer from the 'orders' topic. Dropped ~45% for the same reason: fewer order messages are published to Kafka due to blocked checkout RPCs.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows active oscillating values around 4-6 bytes/s. At 20:58 the value drops to 3.525, then goes to 0 at 20:59 and stays at 0 through 21:04. The signal partially recovers at ~1-2.5 after that but never returns to the pre-incident 4-6 range. The last timestamp showing the active pre-incident pattern is 20:58, marking the onset of the collapse." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for cartFailure flag evaluating to variant 'on'. Was zero before; spiked to ~0.020/s after the flag was flipped on at 21:09:45 UTC.", + "onset_utc": "2026-04-20 21:12:00 UTC", + "onset_offset_seconds": 134, + "onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 21:12:00 UTC, roughly 2 minutes after the incident time of 21:09:45 UTC, which is consistent with the 5m rate window needing time to populate. This first appearance is the onset." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 21:10:16.891 and 21:18:32.951 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T21:10:16.891Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 388 24 15000 - \"-\" \"python-requests/2.32.5\" \"51a1c50a-aae4-9f34-a007-bc1cc79bd191\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:51780 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "Zp-7rJ0Br_RFnSwRCHb6", + "@timestamp": "21:10:16.891" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "UZ-7rJ0Br_RFnSwRu3in", + "@timestamp": "21:11:02.555" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ-7rJ0Br_RFnSwR93lV", + "@timestamp": "21:11:17.818" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5-7rJ0Br_RFnSwR_nkN", + "@timestamp": "21:11:19.277" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1Z-9rJ0Br_RFnSwR2329", + "@timestamp": "21:13:21.589" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "k5--rJ0Br_RFnSwRaH9q", + "@timestamp": "21:13:57.485" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "oJ--rJ0Br_RFnSwRyYAN", + "@timestamp": "21:14:22.110" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "c5-_rJ0Br_RFnSwRn4Pu", + "@timestamp": "21:15:17.506" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "n5_ArJ0Br_RFnSwRTIXp", + "@timestamp": "21:16:01.367" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "HZ_ArJ0Br_RFnSwRqYed", + "@timestamp": "21:16:25.280" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8Z_BrJ0Br_RFnSwRB4dg", + "@timestamp": "21:16:48.941" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ_BrJ0Br_RFnSwRVomV", + "@timestamp": "21:17:09.292" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5_CrJ0Br_RFnSwRJIue", + "@timestamp": "21:18:01.900" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_p_CrJ0Br_RFnSwRVIuL", + "@timestamp": "21:18:14.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Np_CrJ0Br_RFnSwRnY3B", + "@timestamp": "21:18:32.951" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 21:12:36.954 and 21:18:39.671 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "6p-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.954" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Cp--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.969" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "-5_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.671" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 21:12:36.994 and 21:18:39.672 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 40 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "65-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.994" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.970" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IZ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_J_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.672" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 21:10:16 and 21:18:32 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 140–1327 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 140 s and 1327 s across the 15 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "da81017ad4d80fa404b38e5e686886ed", + "@timestamp": "21:18:32", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1327.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "01dbf1eeb70a6f0207d8192cb85e7087", + "@timestamp": "21:18:14", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1224.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d35e675f70f607cbc7f535ce11990750", + "@timestamp": "21:18:01", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1125.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "8ccd4dad719adb45b128029d18f7cb64", + "@timestamp": "21:17:09", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1054.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "449da5463a4da2f53b3e0ab20560d1a6", + "@timestamp": "21:16:48", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "957.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cecc13a9b88bc0a3114e66c0f68286d", + "@timestamp": "21:16:25", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "848.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "12779fc1e046d382708fe0c29e909448", + "@timestamp": "21:16:01", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "756.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "bd7e236996ccb389179dbeff40dc3961", + "@timestamp": "21:15:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "688.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "6ccda48d54e9cd419cbcb4114b3f7f88", + "@timestamp": "21:14:22", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "624.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "7cc56e148ec42ca034321003b04f6361", + "@timestamp": "21:13:57", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "523.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "40ff8f925cd9b5b67c14a11a4cbf8ff9", + "@timestamp": "21:13:21", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "443.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d550968745fedca02a94c025efa59de8", + "@timestamp": "21:11:19", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "440.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0219b564d1854c435e5db02ecff24a69", + "@timestamp": "21:11:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "319.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1f2b90a2166a087db5a7d18072a042cf", + "@timestamp": "21:11:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "219.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cc6277fa9093cda3b77af2ecb275bb6", + "@timestamp": "21:10:16", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "140.1", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-50%.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-paymentFailure-50%.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/test.sh b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-10-univ00-universal_ttd480m_period_same-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubric.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubric.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-cc1-adFailure-on.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-cc1-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-cc1-adFailure-on.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-cartFailure-on.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..9454f12c8c88a1ce7f4ac37f086596f4100ddc0e --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-cartFailure-on.json @@ -0,0 +1,427 @@ +{ + "incident_time": "2026-04-20T21:09:45.917730+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container CPU utilization spiked ~3x (avg 0.17 to 0.51) due to ConnectionMultiplexer.Connect exponential-backoff retry loops against the unreachable badhost:1234 host", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline fluctuates roughly 0.06–0.09 with occasional spikes to ~0.2. After the incident at 21:10, the value at 21:11 (0.135) begins a sustained rise, with subsequent values consistently elevated (0.26, 0.36, 0.25, 0.37, 1.09, etc.), well above the pre-incident baseline. 21:11 is the first post-incident timestamp showing a clear upward departure that persists." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"cart\"}", + "description": "Cart container memory usage jumped from stable ~53MB to avg ~65MB (peak 71MB, +22%) due to accumulating connection objects and retry state from repeated failed connection attempts to badhost:1234", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline is ~53-54 MB. At 21:11 the value jumps to ~56.1 MB, a clear departure from baseline, and continues rising to ~67 MB. This is the first timestamp after the incident time showing a significant spike above the stable pre-incident level." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"EmptyCart\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "gRPC client-side count of successful (code 0) EmptyCart calls from checkout to cart service. Collapsed from ~0.020/s to zero after cartFailure was enabled, because all EmptyCart calls now route to _badCartStore and fail.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows regular activity around 0.017-0.033 req/s. At 20:58 the last typical value (0.0166667) appears, then the signal drops to zero at 20:59 and stays near zero or at drastically reduced levels (~0.004) through the incident time and beyond, never recovering to the pre-incident pattern. This is the last timestamp where the pre-incident active pattern is still present." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(kafka_consumer_bytes_consumed_total{topic=\"orders\"}[5m])", + "description": "Rate of bytes consumed by the fraud-detection Kafka consumer from the 'orders' topic. Dropped ~45% for the same reason: fewer order messages are published to Kafka due to blocked checkout RPCs.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows active oscillating values around 4-6 bytes/s. At 20:58 the value drops to 3.525, then goes to 0 at 20:59 and stays at 0 through 21:04. The signal partially recovers at ~1-2.5 after that but never returns to the pre-incident 4-6 range. The last timestamp showing the active pre-incident pattern is 20:58, marking the onset of the collapse." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for cartFailure flag evaluating to variant 'on'. Was zero before; spiked to ~0.020/s after the flag was flipped on at 21:09:45 UTC.", + "onset_utc": "2026-04-20 21:12:00 UTC", + "onset_offset_seconds": 134, + "onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 21:12:00 UTC, roughly 2 minutes after the incident time of 21:09:45 UTC, which is consistent with the 5m rate window needing time to populate. This first appearance is the onset." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 21:10:16.891 and 21:18:32.951 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T21:10:16.891Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 388 24 15000 - \"-\" \"python-requests/2.32.5\" \"51a1c50a-aae4-9f34-a007-bc1cc79bd191\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:51780 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "Zp-7rJ0Br_RFnSwRCHb6", + "@timestamp": "21:10:16.891" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "UZ-7rJ0Br_RFnSwRu3in", + "@timestamp": "21:11:02.555" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ-7rJ0Br_RFnSwR93lV", + "@timestamp": "21:11:17.818" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5-7rJ0Br_RFnSwR_nkN", + "@timestamp": "21:11:19.277" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1Z-9rJ0Br_RFnSwR2329", + "@timestamp": "21:13:21.589" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "k5--rJ0Br_RFnSwRaH9q", + "@timestamp": "21:13:57.485" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "oJ--rJ0Br_RFnSwRyYAN", + "@timestamp": "21:14:22.110" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "c5-_rJ0Br_RFnSwRn4Pu", + "@timestamp": "21:15:17.506" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "n5_ArJ0Br_RFnSwRTIXp", + "@timestamp": "21:16:01.367" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "HZ_ArJ0Br_RFnSwRqYed", + "@timestamp": "21:16:25.280" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8Z_BrJ0Br_RFnSwRB4dg", + "@timestamp": "21:16:48.941" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ_BrJ0Br_RFnSwRVomV", + "@timestamp": "21:17:09.292" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5_CrJ0Br_RFnSwRJIue", + "@timestamp": "21:18:01.900" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_p_CrJ0Br_RFnSwRVIuL", + "@timestamp": "21:18:14.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Np_CrJ0Br_RFnSwRnY3B", + "@timestamp": "21:18:32.951" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 21:12:36.954 and 21:18:39.671 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "6p-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.954" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Cp--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.969" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "-5_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.671" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 21:12:36.994 and 21:18:39.672 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 40 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "65-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.994" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.970" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IZ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_J_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.672" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 21:10:16 and 21:18:32 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 140–1327 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 140 s and 1327 s across the 15 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "da81017ad4d80fa404b38e5e686886ed", + "@timestamp": "21:18:32", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1327.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "01dbf1eeb70a6f0207d8192cb85e7087", + "@timestamp": "21:18:14", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1224.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d35e675f70f607cbc7f535ce11990750", + "@timestamp": "21:18:01", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1125.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "8ccd4dad719adb45b128029d18f7cb64", + "@timestamp": "21:17:09", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1054.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "449da5463a4da2f53b3e0ab20560d1a6", + "@timestamp": "21:16:48", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "957.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cecc13a9b88bc0a3114e66c0f68286d", + "@timestamp": "21:16:25", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "848.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "12779fc1e046d382708fe0c29e909448", + "@timestamp": "21:16:01", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "756.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "bd7e236996ccb389179dbeff40dc3961", + "@timestamp": "21:15:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "688.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "6ccda48d54e9cd419cbcb4114b3f7f88", + "@timestamp": "21:14:22", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "624.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "7cc56e148ec42ca034321003b04f6361", + "@timestamp": "21:13:57", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "523.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "40ff8f925cd9b5b67c14a11a4cbf8ff9", + "@timestamp": "21:13:21", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "443.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d550968745fedca02a94c025efa59de8", + "@timestamp": "21:11:19", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "440.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0219b564d1854c435e5db02ecff24a69", + "@timestamp": "21:11:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "319.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1f2b90a2166a087db5a7d18072a042cf", + "@timestamp": "21:11:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "219.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cc6277fa9093cda3b77af2ecb275bb6", + "@timestamp": "21:10:16", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "140.1", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-50%.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-paymentFailure-50%.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/solve.py b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/solve.sh b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/expected.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0c2bfac7045afe5a797c0bd9b75cd10a38d0a9fd --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/expected.json @@ -0,0 +1,29 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:39:39.920177+00:00" + }, + { + "event_id": "d2-cc1-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-20T15:08:20.478349+00:00" + }, + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + }, + { + "event_id": "d2-d1dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-20T20:09:32.298358+00:00" + }, + { + "event_id": "d2-d1dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-20T21:09:45.917730+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-cc1-adFailure-on.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-cc1-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..917490a22ec4e7c3edd83dde6bca26eb8cb948d4 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-cc1-adFailure-on.json @@ -0,0 +1,245 @@ +{ + "incident_time": "2026-04-20T15:08:20.478349+00:00", + "feature_flag": "adFailure", + "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.", + "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.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC server-side error count for AdService GetAds calls returning UNAVAILABLE (status 14). New series appeared after adFailure flag activation, as StatusRuntimeException(Status.UNAVAILABLE) is thrown with 1/10 probability.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric type, meaning the series appeared after the incident. The incident occurred at 15:08:20 UTC and the first data point in the series is at 15:12:00 UTC, indicating the metric was created at that time. The series did not exist before the incident, and its appearance at 15:12:00 represents the onset of error responses (gRPC status code 14) for the AdService GetAds RPC." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Cumulative request duration for failed AdService GetAds gRPC calls with UNAVAILABLE status. Tracks total server-side processing time spent on requests that hit the adFailure flag path.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This metric type is 'created', meaning it appeared for the first time after the incident. The incident occurred at 15:08:20 UTC and the very first data point in the series is at 15:12:00 UTC with a non-zero value of 0.0498, indicating the rpc_server_duration for status_code=14 (UNAVAILABLE) began being emitted shortly after the incident. Since there are no data points before 15:12:00, this is the onset — the first observation of this newly created error metric." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_service": "oteldemo.AdService" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_count{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Count of gRPC server response messages for AdService calls that returned UNAVAILABLE error. New series created when adFailure flag began triggering failures.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "This is a 'created' metric (rpc_grpc_status_code=14 errors for AdService). The series begins at 15:12:00 UTC, which is the first data point after the incident at 15:08:20 UTC. Since this metric didn't exist before the incident, the onset is when it first appears. The ~4 minute delay is consistent with the 5m rate window needing time to accumulate counts after errors begin." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_server_response_size_bytes_sum{rpc_service=\"oteldemo.AdService\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "Total gRPC server response bytes for AdService UNAVAILABLE error responses. Tracks the size of error response payloads sent back to the frontend.", + "onset_utc": "2026-04-20 15:12:00 UTC", + "onset_offset_seconds": 219, + "onset_reasoning": "Metric type is 'created' — this series (rpc_grpc_status_code=14, i.e. UNAVAILABLE errors for AdService) did not exist before the incident. The first data point appears at 15:12:00 UTC, approximately 4 minutes after the incident injection at 15:08:20, which aligns with the 5m rate window needing time to populate. This is the onset of the new error signal." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",target=\"/api/data\",status=\"500\"}[5m])", + "description": "Custom frontend application counter for GET /api/data requests returning HTTP 500. Rate spiked from zero after the adFailure flag caused gRPC errors to propagate as 500s on the /api/data endpoint.", + "onset_utc": "2026-04-20 15:11:00 UTC", + "onset_offset_seconds": 159, + "onset_reasoning": "The metric is flat at 0 from the start of the window through 15:10. At 15:11 it first rises to ~0.0042, marking the initial spike above the zero baseline, approximately 3 minutes after the incident time." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500", + "net_peer_name": "frontend-proxy", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_count{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Load generator HTTP client receiving 500 errors from frontend-proxy. Rate went from zero to non-zero as the ad service failures cascaded through the frontend to the external client.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it first rises to ~0.004, which is the first non-zero value after the incident time (15:08). This marks the clear onset of the HTTP 500 spike." + }, + { + "type": "spiked", + "query": "rate(http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_status_code=\"500\",net_peer_name=\"frontend-proxy\"}[5m])", + "description": "Cumulative HTTP client request duration for load generator requests that received 500 from frontend-proxy due to the ad service failure cascade.", + "onset_utc": "2026-04-20 15:10:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "The metric is flat at 0 from 14:48 through 15:09. At 15:10 it jumps to 0.228, marking the first clear spike above the zero baseline. This is consistent with the incident at 15:08, with a ~2-minute propagation delay through the 5m rate window." + } + ] + }, + { + "metric_family": "feature_flag_flagd_result_reason", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "adFailure" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_result_reason_total{feature_flag_key=\"adFailure\"}[5m])", + "description": "flagd evaluation result reason counter for the adFailure flag. Incremented when flagd resolved the adFailure flag (STATIC reason), coinciding with the flag being toggled on.", + "onset_utc": "2026-04-20 15:09:00 UTC", + "onset_offset_seconds": 39, + "onset_reasoning": "The metric is flat at 0 from 14:49 through 15:08 (incident time). At 15:09 it spikes to ~0.00417, sustaining for a few minutes (15:09–15:12), which is the first clear rise above the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 15:09:27 and 15:16:14 UTC, GET /api/data?contextKeys={category} returned 500 errors three times (3 failures out of 25 completed /api/data requests after the incident, ~12%, matching the 1/10 probabilistic failure rate). Each failing request shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~10-50 ms later. The three failing requests sample different categories (travel, books, telescopes).", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T15:09:27.734Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 48 48 \"-\" \"python-requests/2.32.5\" \"5570480f-1ad2-9163-aac4-ff388352596a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "a9714bdfc6d2fb07" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1ptwq50Br_RFnSwRemHk", + "@timestamp": "15:09:27.734" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJtxq50Br_RFnSwRRmSL", + "@timestamp": "15:10:19.847" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "MJt2q50Br_RFnSwRrXgq", + "@timestamp": "15:16:14.441" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 15:09:27 and 15:16:14 UTC, the ad service emitted 3 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~10-50 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 3 failing traces under that cluster).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "78b32363779706cd748895d77f56d844", + "spanId": "99899da46f430d35" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "uZtwq50Br_RFnSwRd2HN", + "@timestamp": "15:09:27.776" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Pptxq50Br_RFnSwRRmRY", + "@timestamp": "15:10:19.859" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Ppt2q50Br_RFnSwRr3gE", + "@timestamp": "15:16:14.450" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 15:09:27 and 15:16:14 UTC, 3 traces show ad:oteldemo.AdService/GetAds failing with gRPC status 14 UNAVAILABLE and cascading through the frontend /api/data path. All 3 traces have root operation load-generator:user_get_ads. The 3 failures span ~7 minutes, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1-2 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[telescopes], [books], or [travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "78b32363779706cd748895d77f56d844", + "@timestamp": "15:09:27", + "user_action": "user_get_ads" + }, + { + "traceID": "594cefb047aa9caa2c8acf85f2aafa8b", + "@timestamp": "15:10:19", + "user_action": "user_get_ads" + }, + { + "traceID": "1221c4c4d070604b6603185e6f679eda", + "@timestamp": "15:16:14", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-cartFailure-on.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..9454f12c8c88a1ce7f4ac37f086596f4100ddc0e --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-cartFailure-on.json @@ -0,0 +1,427 @@ +{ + "incident_time": "2026-04-20T21:09:45.917730+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container CPU utilization spiked ~3x (avg 0.17 to 0.51) due to ConnectionMultiplexer.Connect exponential-backoff retry loops against the unreachable badhost:1234 host", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline fluctuates roughly 0.06–0.09 with occasional spikes to ~0.2. After the incident at 21:10, the value at 21:11 (0.135) begins a sustained rise, with subsequent values consistently elevated (0.26, 0.36, 0.25, 0.37, 1.09, etc.), well above the pre-incident baseline. 21:11 is the first post-incident timestamp showing a clear upward departure that persists." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"cart\"}", + "description": "Cart container memory usage jumped from stable ~53MB to avg ~65MB (peak 71MB, +22%) due to accumulating connection objects and retry state from repeated failed connection attempts to badhost:1234", + "onset_utc": "2026-04-20 21:11:00 UTC", + "onset_offset_seconds": 74, + "onset_reasoning": "Pre-incident baseline is ~53-54 MB. At 21:11 the value jumps to ~56.1 MB, a clear departure from baseline, and continues rising to ~67 MB. This is the first timestamp after the incident time showing a significant spike above the stable pre-incident level." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"EmptyCart\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "gRPC client-side count of successful (code 0) EmptyCart calls from checkout to cart service. Collapsed from ~0.020/s to zero after cartFailure was enabled, because all EmptyCart calls now route to _badCartStore and fail.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows regular activity around 0.017-0.033 req/s. At 20:58 the last typical value (0.0166667) appears, then the signal drops to zero at 20:59 and stays near zero or at drastically reduced levels (~0.004) through the incident time and beyond, never recovering to the pre-incident pattern. This is the last timestamp where the pre-incident active pattern is still present." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(kafka_consumer_bytes_consumed_total{topic=\"orders\"}[5m])", + "description": "Rate of bytes consumed by the fraud-detection Kafka consumer from the 'orders' topic. Dropped ~45% for the same reason: fewer order messages are published to Kafka due to blocked checkout RPCs.", + "onset_utc": "2026-04-20 20:58:00 UTC", + "onset_offset_seconds": -705, + "onset_reasoning": "The pre-incident baseline shows active oscillating values around 4-6 bytes/s. At 20:58 the value drops to 3.525, then goes to 0 at 20:59 and stays at 0 through 21:04. The signal partially recovers at ~1-2.5 after that but never returns to the pre-incident 4-6 range. The last timestamp showing the active pre-incident pattern is 20:58, marking the onset of the collapse." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for cartFailure flag evaluating to variant 'on'. Was zero before; spiked to ~0.020/s after the flag was flipped on at 21:09:45 UTC.", + "onset_utc": "2026-04-20 21:12:00 UTC", + "onset_offset_seconds": 134, + "onset_reasoning": "This is a 'created' metric — the series did not exist before the incident. The first data point appears at 21:12:00 UTC, roughly 2 minutes after the incident time of 21:09:45 UTC, which is consistent with the 5m rate window needing time to populate. This first appearance is the onset." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 21:10:16.891 and 21:18:32.951 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-20T21:10:16.891Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 388 24 15000 - \"-\" \"python-requests/2.32.5\" \"51a1c50a-aae4-9f34-a007-bc1cc79bd191\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:51780 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "Zp-7rJ0Br_RFnSwRCHb6", + "@timestamp": "21:10:16.891" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "UZ-7rJ0Br_RFnSwRu3in", + "@timestamp": "21:11:02.555" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ-7rJ0Br_RFnSwR93lV", + "@timestamp": "21:11:17.818" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5-7rJ0Br_RFnSwR_nkN", + "@timestamp": "21:11:19.277" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1Z-9rJ0Br_RFnSwR2329", + "@timestamp": "21:13:21.589" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "k5--rJ0Br_RFnSwRaH9q", + "@timestamp": "21:13:57.485" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "oJ--rJ0Br_RFnSwRyYAN", + "@timestamp": "21:14:22.110" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "c5-_rJ0Br_RFnSwRn4Pu", + "@timestamp": "21:15:17.506" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "n5_ArJ0Br_RFnSwRTIXp", + "@timestamp": "21:16:01.367" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "HZ_ArJ0Br_RFnSwRqYed", + "@timestamp": "21:16:25.280" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8Z_BrJ0Br_RFnSwRB4dg", + "@timestamp": "21:16:48.941" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ_BrJ0Br_RFnSwRVomV", + "@timestamp": "21:17:09.292" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "j5_CrJ0Br_RFnSwRJIue", + "@timestamp": "21:18:01.900" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_p_CrJ0Br_RFnSwRVIuL", + "@timestamp": "21:18:14.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Np_CrJ0Br_RFnSwRnY3B", + "@timestamp": "21:18:32.951" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 21:12:36.954 and 21:18:39.671 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "6p-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.954" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Cp--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.969" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "-5_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.671" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 21:12:36.994 and 21:18:39.672 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 40 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "9cc6277fa9093cda3b77af2ecb275bb6", + "spanId": "24ac200bdf8854a5", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "65-9rJ0Br_RFnSwRAns9", + "@timestamp": "21:12:36.994" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ--rJ0Br_RFnSwR6oGT", + "@timestamp": "21:14:41.970" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IZ_ArJ0Br_RFnSwRrYcs", + "@timestamp": "21:16:36.991" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "_J_CrJ0Br_RFnSwRgYz8", + "@timestamp": "21:18:39.672" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 21:10:16 and 21:18:32 UTC (30 s to ~8.8 min after cartFailure was flipped on at 21:09:45 UTC), 15 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 140–1327 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 140 s and 1327 s across the 15 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "da81017ad4d80fa404b38e5e686886ed", + "@timestamp": "21:18:32", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1327.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "01dbf1eeb70a6f0207d8192cb85e7087", + "@timestamp": "21:18:14", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1224.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d35e675f70f607cbc7f535ce11990750", + "@timestamp": "21:18:01", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1125.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "8ccd4dad719adb45b128029d18f7cb64", + "@timestamp": "21:17:09", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "1054.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "449da5463a4da2f53b3e0ab20560d1a6", + "@timestamp": "21:16:48", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "957.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cecc13a9b88bc0a3114e66c0f68286d", + "@timestamp": "21:16:25", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "848.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "12779fc1e046d382708fe0c29e909448", + "@timestamp": "21:16:01", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "756.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "bd7e236996ccb389179dbeff40dc3961", + "@timestamp": "21:15:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "688.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "6ccda48d54e9cd419cbcb4114b3f7f88", + "@timestamp": "21:14:22", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "624.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "7cc56e148ec42ca034321003b04f6361", + "@timestamp": "21:13:57", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "523.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "40ff8f925cd9b5b67c14a11a4cbf8ff9", + "@timestamp": "21:13:21", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "443.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "d550968745fedca02a94c025efa59de8", + "@timestamp": "21:11:19", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "440.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0219b564d1854c435e5db02ecff24a69", + "@timestamp": "21:11:17", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "319.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1f2b90a2166a087db5a7d18072a042cf", + "@timestamp": "21:11:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "219.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9cc6277fa9093cda3b77af2ecb275bb6", + "@timestamp": "21:10:16", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "140.1", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..8f433a4c891c465f6fd7993bb75e2a4af844355c --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-10%.json @@ -0,0 +1,184 @@ +{ + "incident_time": "2026-04-20T20:09:32.298358+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service Charge RPC errors. This series was zero before the incident and appeared when the paymentFailure flag began causing charge.js to throw 'Payment request failed' at a 10% rate.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error-rate values (0.006–0.004) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.0042 and then steadily climbs (doubling by 20:25 and tripling by 20:27–20:29), indicating new errors being generated by the incident. The first timestamp of this new, sustained rise is 20:22." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative error-span duration for payment service Charge RPC. This series was zero before the incident and appeared as failed charge spans began accumulating milliseconds of error latency.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is zero from 20:13 through 20:21 (pre-incident baseline). At 20:22 it first rises to 0.0042378, marking the creation of error span duration for the payment service Charge endpoint. This is the first non-zero value after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric is a 'created' type. The series is flat at 0 from 20:12 through 20:21, then first appears with a non-zero value (0.00416667) at 20:22, indicating the metric was created at that point following the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "All values in the series are 0 throughout the entire observation window (20:12-20:29). Despite the metric type being 'created', there is no timestamp where the rate rises above zero, so no clear onset of the feature flag being evaluated is visible in this data." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\", span_name=\"oteldemo.PaymentService/Charge\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for checkout service's outbound call to PaymentService/Charge that returned errors. This series was zero before the incident and appeared as the checkout service observed payment charge failures propagating back as gRPC errors.", + "onset_utc": "2026-04-20 20:22:00 UTC", + "onset_offset_seconds": 747, + "onset_reasoning": "The metric type is 'created'. Before the incident, there are some residual error spans (20:13–20:16) that decay to zero by 20:17. The series stays at zero from 20:17–20:21. At 20:22 the error rate reappears at ~0.004/s and then steadily climbs to ~0.0125/s, indicating the new, sustained error pattern created by the incident. The onset is 20:22, the first timestamp where the signal emerges from the zero baseline after the incident." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:10:09 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "zJ6DrJ0Br_RFnSwRxMfq", + "@timestamp": "20:10:09.863" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:10:09 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "R56DrJ0Br_RFnSwR2sgg", + "@timestamp": "20:10:09.903" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:10:09 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "4ebb13b0d72ab3950c6647f9ead695e2", + "@timestamp": "20:10:09", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-50%.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb628a82a2cd8e3dca1b8d07d8446ccb87436804 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-paymentFailure-50%.json @@ -0,0 +1,251 @@ +{ + "incident_time": "2026-04-20T20:39:39.920177+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 0 to 29.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. The first non-zero value after the incident (20:39:39) appears at 20:43 (0.00417), marking the start of a sustained spike that grows to ~0.017-0.021 and persists through the end of the window." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 0 to 33.93ms as 29 payment failures accumulated.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33 through 20:42. At 20:43 the metric rises to ~0.00436 and remains elevated thereafter, marking the sustained post-incident spike onset." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39:39, the metric first rises above zero at 20:43 (0.00416665) and continues to increase, reaching sustained higher values (0.012-0.021) indicating a clear spike onset." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outgoing gRPC calls to PaymentService/Charge failing with UNKNOWN (code 2) spiked ~171% during the incident. The payment service throws 'Payment request failed. Invalid token.' with 50% probability, which the gRPC layer surfaces as UNKNOWN to the checkout client.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. After the incident at 20:39, the metric first rises above zero at 20:43 (0.00416667), then continues climbing to sustained higher values (0.0125-0.0167), indicating the spike onset." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "POST", + "http_status_code": "500", + "service_name": "frontend" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(http_server_duration_milliseconds_count{service_name=\"frontend\",http_method=\"POST\",http_status_code=\"500\"}[5m])", + "description": "Frontend HTTP POST 500 error rate spiked ~119% during the incident. When checkout PlaceOrder returns gRPC INTERNAL, the frontend proxies it as HTTP 500 to the browser on POST /api/checkout.", + "onset_utc": "2026-04-20 20:43:00 UTC", + "onset_offset_seconds": 200, + "onset_reasoning": "Pre-incident baseline is 0 from 20:33-20:42. At 20:43 the metric rises to ~0.004 and continues climbing to sustained values around 0.012-0.017, clearly above the zero baseline. This is the first post-incident timestamp where the spike begins." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag's '50%' variant appeared at 20:41 UTC (from non-existent to 1), confirming the flag was activated to the 50% failure variant at the incident start time.", + "onset_utc": "2026-04-20 20:41:00 UTC", + "onset_offset_seconds": 80, + "onset_reasoning": "This is a 'created' metric type. The time series did not exist before the incident at 20:39:39 UTC. The first data point appears at 20:41:00 UTC with value 1, indicating the feature flag variant '50%' was first evaluated at that time, consistent with the paymentFailure flag being toggled on." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "aJ-grJ0Br_RFnSwRjST_", + "@timestamp": "20:41:36.308" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "uJ-irJ0Br_RFnSwRNilk", + "@timestamp": "20:43:24.770" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "DJ-irJ0Br_RFnSwR-yw7", + "@timestamp": "20:44:14.886" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "QJ-jrJ0Br_RFnSwRZy0f", + "@timestamp": "20:44:42.161" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "IJ-mrJ0Br_RFnSwRbDer", + "@timestamp": "20:48:00.737" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–29ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "1p-grJ0Br_RFnSwRoySH", + "@timestamp": "20:41:36.327" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Q5-irJ0Br_RFnSwRSSri", + "@timestamp": "20:43:24.790" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "RZ-jrJ0Br_RFnSwRDSxl", + "@timestamp": "20:44:14.908" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "3J-jrJ0Br_RFnSwRdy0T", + "@timestamp": "20:44:42.190" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "m5-mrJ0Br_RFnSwRgTe1", + "@timestamp": "20:48:00.763" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:41:36 and 20:48:00 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "1f0b382816b66525b8bc2261527db8a8", + "@timestamp": "20:41:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "7671b52e833c8a221b9a4c12a71dddd0", + "@timestamp": "20:43:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d745ba14a2b6bac8bb38f7b57b7a6ad1", + "@timestamp": "20:44:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6ff8bf68e186051f551b3becf8b80aaf", + "@timestamp": "20:44:42", + "user_action": "user_checkout_multi" + }, + { + "traceID": "c21e75641fc0d69a3bb5ac41335e1d3a", + "@timestamp": "20:48:00", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/test.sh b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-paymentfailure-50-univ00-universal_ttd60m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/rubric.json b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.py b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.sh b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/expected.json b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0907ea585318d1e75b26798ca2a77fd1b2996aff --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/test.sh b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_period_same-period/environment/Dockerfile b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/rubric.json b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/solve.py b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/solve.sh b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/expected.json b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0907ea585318d1e75b26798ca2a77fd1b2996aff --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/test.sh b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-00-hard_ttd480m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/rubric.json b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/solve.py b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/solve.sh b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/expected.json b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0907ea585318d1e75b26798ca2a77fd1b2996aff --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/test.sh b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/environment/Dockerfile b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/environment/docker-compose.yaml b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/rubric.json b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/rubric.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/solve.py b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/solve.sh b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/expected.json b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0907ea585318d1e75b26798ca2a77fd1b2996aff --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/test.sh b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-06-medium_ttd480m_period_same-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0907ea585318d1e75b26798ca2a77fd1b2996aff --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d2-d1dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-20T18:39:10.295601+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cec1d6480330edd31ade647e21aedef040e62821 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/rubrics/d2-d1dep-productCatalogFailure-on.json @@ -0,0 +1,467 @@ +{ + "incident_time": "2026-04-20T18:39:10.295601+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "sum(rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m]))", + "description": "gRPC Internal (code 13) errors on product-catalog's GetProduct method, caused directly by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created', meaning it did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10 UTC), showing rpc_grpc_status_code=13 (INTERNAL) errors beginning on the product-catalog GetProduct endpoint. This is the first timestamp the series exists." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for product-catalog GetProduct — direct effect of the productCatalogFailure flag causing GetProduct for OLJCESPC7Z to return gRPC Internal errors", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the metric begins reporting error span calls for ProductCatalogService/GetProduct starting at this timestamp, consistent with the incident triggering new errors." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call rate for frontend's gRPC client call to GetProduct — the frontend receives the gRPC Internal error from the product-catalog service", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time (18:39:10), indicating this is when the error rate metric was first generated." + } + ] + }, + { + "metric_family": "http_server_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_status_code": "500" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(http_server_duration_milliseconds_count{http_status_code=\"500\"}[5m]))", + "description": "Overall HTTP 500 responses from the frontend server (OTel auto-instrumented), combining both product page and recommendations failures", + "onset_utc": "2026-04-20 18:41:00 UTC", + "onset_offset_seconds": 109, + "onset_reasoning": "The metric is flat at 0 from 18:19 through 18:40. At 18:41 it first rises to 0.00417, marking the initial spike above the zero baseline, consistent with the incident at 18:39 plus the 5m rate window lag." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration rate for product-catalog GetProduct errors — accumulates total milliseconds spent on failed GetProduct calls (errors return sub-2ms)", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series did not exist before the incident. The first data point appears at 18:42:00 UTC, approximately 3 minutes after the incident time of 18:39:10 UTC. This is the onset — the first timestamp where the newly created error-duration rate becomes visible, consistent with the ~5m rate window lag." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration count rate for product-catalog GetProduct — number of error duration observations per second, mirrors calls_total", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 18:42:00 UTC, roughly 3 minutes after the incident time of 18:39:10 UTC, which aligns with the 5m rate window needing time to populate. This is the onset — the metric begins appearing as error spans are generated by the injected fault." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket rate for product-catalog GetProduct — all error spans fall into the le=2ms bucket, confirming fast gRPC error returns", + "onset_utc": "2026-04-20 18:42:00 UTC", + "onset_offset_seconds": 169, + "onset_reasoning": "Metric type is 'created' — this error-status span metric did not exist before the incident. The first data point appears at 18:42:00 UTC (~3 minutes after the incident at 18:39:10), which is when error spans from ProductCatalogService/GetProduct first register in the 5m rate window." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:39:19 and 18:49:07 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "DZ0wrJ0Br_RFnSwRm8yy", + "@timestamp": "18:39:19.342" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "V50yrJ0Br_RFnSwRONEP", + "@timestamp": "18:41:05.339" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "JJ0zrJ0Br_RFnSwRBdRm", + "@timestamp": "18:41:57.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "050zrJ0Br_RFnSwRQdTm", + "@timestamp": "18:42:13.405" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "H50zrJ0Br_RFnSwR5NYh", + "@timestamp": "18:42:54.255" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRB9ZP", + "@timestamp": "18:43:03.654" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Lp01rJ0Br_RFnSwRldzr", + "@timestamp": "18:44:45.353" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "mZ03rJ0Br_RFnSwRMuEj", + "@timestamp": "18:46:31.320" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "1J03rJ0Br_RFnSwRV-FG", + "@timestamp": "18:46:40.472" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "TZ03rJ0Br_RFnSwRguI-", + "@timestamp": "18:46:51.546" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "hJ03rJ0Br_RFnSwRq-JO", + "@timestamp": "18:47:02.567" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "8p03rJ0Br_RFnSwRzuKc", + "@timestamp": "18:47:11.205" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Vp03rJ0Br_RFnSwR4ONF", + "@timestamp": "18:47:15.667" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "6p05rJ0Br_RFnSwRk-ed", + "@timestamp": "18:49:07.660" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:40:20 and 18:49:02 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-20", + "_id": "XJ0xrJ0Br_RFnSwRis8k", + "@timestamp": "18:40:20.432" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "s50xrJ0Br_RFnSwRrc9W", + "@timestamp": "18:40:29.876" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "S50zrJ0Br_RFnSwRItSs", + "@timestamp": "18:42:05.360" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "M50zrJ0Br_RFnSwR8dbH", + "@timestamp": "18:42:57.865" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "fZ00rJ0Br_RFnSwRqdlv", + "@timestamp": "18:43:45.023" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "W502rJ0Br_RFnSwRreBc", + "@timestamp": "18:45:57.044" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "NJ02rJ0Br_RFnSwR9eGj", + "@timestamp": "18:46:15.295" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "Mp03rJ0Br_RFnSwReOJ1", + "@timestamp": "18:46:48.956" + }, + { + "_index": "otel-logs-2026-04-20", + "_id": "w505rJ0Br_RFnSwRg-ft", + "@timestamp": "18:49:02.880" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:39:19 and 18:49:07 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (12), user_add_to_cart (2). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6a259deef7704056e1dec39b52f29e56", + "@timestamp": "18:49:07", + "user_action": "user_browse_product" + }, + { + "traceID": "83207d08a502ab7dd354d872015a2370", + "@timestamp": "18:47:15", + "user_action": "user_browse_product" + }, + { + "traceID": "9a0baf8858ca8c8767c7846659872cc2", + "@timestamp": "18:47:11", + "user_action": "user_browse_product" + }, + { + "traceID": "021d235d56cdae37f8b7ef1fa5240d2a", + "@timestamp": "18:47:02", + "user_action": "user_browse_product" + }, + { + "traceID": "fac990bee3166da4ccc2a24a5b4119c8", + "@timestamp": "18:46:51", + "user_action": "user_browse_product" + }, + { + "traceID": "70510dd93e8294eb9ec6b112358be30b", + "@timestamp": "18:46:40", + "user_action": "user_browse_product" + }, + { + "traceID": "9d2e8e1b77a17ff0f7146fbe1d6c1f61", + "@timestamp": "18:46:31", + "user_action": "user_browse_product" + }, + { + "traceID": "aaea2dc60701b3bf76d5e9d77b96a091", + "@timestamp": "18:44:45", + "user_action": "user_browse_product" + }, + { + "traceID": "b3321fa4b3555c7483ade24f16f84abf", + "@timestamp": "18:43:03", + "user_action": "user_browse_product" + }, + { + "traceID": "a9e947563a3a3ad6943e627e31e00e77", + "@timestamp": "18:42:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "9415bd24a285236ecd6252c221704485", + "@timestamp": "18:42:13", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0f651e8eadeaa6a2258686370862bdc4", + "@timestamp": "18:41:57", + "user_action": "user_browse_product" + }, + { + "traceID": "14cc43afc033a3cf08f74d8495f27ddb", + "@timestamp": "18:41:05", + "user_action": "user_browse_product" + }, + { + "traceID": "51f33079f5421e2f18271615c855d2cb", + "@timestamp": "18:39:19", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:40:20 and 18:49:02 UTC, 9 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6601d09575f0ad1068d42ddb02aca45f", + "@timestamp": "18:49:02", + "user_action": "user_get_recommendations" + }, + { + "traceID": "8b6e47a061c8fdf2d91b8e4f873feeb6", + "@timestamp": "18:46:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e289d7505b5f6f37da83a30541ba7e38", + "@timestamp": "18:46:15", + "user_action": "user_get_recommendations" + }, + { + "traceID": "174eb95fce4255ce66a8a60ba05edb5c", + "@timestamp": "18:45:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02884bb69481997f4e2948b6ddafd4da", + "@timestamp": "18:43:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "a070d8fdba4952146828d77d2d5f1489", + "@timestamp": "18:42:57", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ca641468f07ab30257ea0a0aacee1884", + "@timestamp": "18:42:05", + "user_action": "user_get_recommendations" + }, + { + "traceID": "374fe073d5cf0f0f0b727277f9c42691", + "@timestamp": "18:40:29", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef32d4eec477274916226faa53979d68", + "@timestamp": "18:40:20", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d2-d1dep-productcatalogfailure-on-11-easy_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/environment/Dockerfile b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/environment/docker-compose.yaml b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/check_prediction.py b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubric.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubric.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/solve.py b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/solve.sh b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/check_prediction.py b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/expected.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d101d7ea9e94e8fd13cf71a1aba8887d62886401 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d3-d2dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:16:12.513046+00:00" + }, + { + "event_id": "d3-d2dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-21T18:45:50.326565+00:00" + }, + { + "event_id": "d3-d2dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:46:18.899501+00:00" + }, + { + "event_id": "d3-d2dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-21T21:16:26.836862+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/test.sh b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-01-hard_ttd480m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubric.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.py b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.sh b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/expected.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..37fbffce09c38d18a3717cce414db75efc4e2a64 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,29 @@ +{ + "events": [ + { + "event_id": "d3-d2dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:16:12.513046+00:00" + }, + { + "event_id": "d3-d2dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-21T18:45:50.326565+00:00" + }, + { + "event_id": "d3-d2dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:46:18.899501+00:00" + }, + { + "event_id": "d3-d2dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-21T21:16:26.836862+00:00" + }, + { + "event_id": "d4-d3dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-22T18:52:17.653473+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/test.sh b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/environment/Dockerfile b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/environment/docker-compose.yaml b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/check_prediction.py b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubric.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubric.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/solve.py b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/solve.sh b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/check_prediction.py b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/expected.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d101d7ea9e94e8fd13cf71a1aba8887d62886401 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d3-d2dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:16:12.513046+00:00" + }, + { + "event_id": "d3-d2dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-21T18:45:50.326565+00:00" + }, + { + "event_id": "d3-d2dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:46:18.899501+00:00" + }, + { + "event_id": "d3-d2dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-21T21:16:26.836862+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/test.sh b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-10-02-medium_ttd480m_period_same-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubric.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..e55cb50e5ea8db42bed372710d0f6b475b1f759c --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-paymentFailure-10%.json @@ -0,0 +1,200 @@ +{ + "incident_time": "2026-04-22T20:22:41.236522+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the payment service's Charge RPC. Was zero before the incident; the paymentFailure flag causes ~10% of charge calls to throw, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram count for payment Charge errors. Was zero before the incident; each failed charge produces a duration sample in this histogram.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:28. The first non-zero value appears at 20:29 (0.00416667), which is about 6 minutes after the incident time. This is the clear onset of the spike above the zero baseline." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration sum for payment Charge errors. Was zero before the incident; tracks cumulative latency of failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00426, which is the first non-zero value after the incident time (20:22:41). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram buckets for payment Charge errors. Was zero before the incident; populates latency distribution buckets for failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The baseline is 0 throughout the pre-incident period. After the incident at 20:22:41 UTC, the metric remains at 0 until 20:29:00 UTC when it first spikes to 0.0708333, clearly rising above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": "2026-04-22 20:24:00 UTC", + "onset_offset_seconds": 78, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:23. At 20:24 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"checkout\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the checkout service's client-side PaymentService/Charge span. Was zero before the incident; errors from the payment service propagate as gRPC errors on the checkout side.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:27:53 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "IsXgtp0Br_RFnSwRubU5", + "@timestamp": "20:27:53.167" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:27:53 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "ksXgtp0Br_RFnSwRy7W0", + "@timestamp": "20:27:53.198" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:27:53 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2de5b0fee49445b07e09b4338ca9f884", + "@timestamp": "20:27:53", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/solve.py b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/solve.sh b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/expected.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f08f4cbd251f8085ec198f4207548f9e58532e77 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,29 @@ +{ + "events": [ + { + "event_id": "d3-d2dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:46:18.899501+00:00" + }, + { + "event_id": "d3-d2dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-21T18:45:50.326565+00:00" + }, + { + "event_id": "d3-d2dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:16:12.513046+00:00" + }, + { + "event_id": "d4-d3dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-22T18:52:17.653473+00:00" + }, + { + "event_id": "d4-d3dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-22T20:22:41.236522+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..e55cb50e5ea8db42bed372710d0f6b475b1f759c --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-paymentFailure-10%.json @@ -0,0 +1,200 @@ +{ + "incident_time": "2026-04-22T20:22:41.236522+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the payment service's Charge RPC. Was zero before the incident; the paymentFailure flag causes ~10% of charge calls to throw, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram count for payment Charge errors. Was zero before the incident; each failed charge produces a duration sample in this histogram.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:28. The first non-zero value appears at 20:29 (0.00416667), which is about 6 minutes after the incident time. This is the clear onset of the spike above the zero baseline." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration sum for payment Charge errors. Was zero before the incident; tracks cumulative latency of failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00426, which is the first non-zero value after the incident time (20:22:41). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram buckets for payment Charge errors. Was zero before the incident; populates latency distribution buckets for failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The baseline is 0 throughout the pre-incident period. After the incident at 20:22:41 UTC, the metric remains at 0 until 20:29:00 UTC when it first spikes to 0.0708333, clearly rising above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": "2026-04-22 20:24:00 UTC", + "onset_offset_seconds": 78, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:23. At 20:24 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"checkout\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the checkout service's client-side PaymentService/Charge span. Was zero before the incident; errors from the payment service propagate as gRPC errors on the checkout side.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:27:53 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "IsXgtp0Br_RFnSwRubU5", + "@timestamp": "20:27:53.167" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:27:53 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "ksXgtp0Br_RFnSwRy7W0", + "@timestamp": "20:27:53.198" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:27:53 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2de5b0fee49445b07e09b4338ca9f884", + "@timestamp": "20:27:53", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/test.sh b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/environment/Dockerfile b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/environment/docker-compose.yaml b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/check_prediction.py b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubric.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubric.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/solve.py b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/solve.sh b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/check_prediction.py b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/expected.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..70b049f4fbfa61d6f53bc24d1537513a18c55ad4 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d3-d2dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:46:18.899501+00:00" + }, + { + "event_id": "d3-d2dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-21T18:45:50.326565+00:00" + }, + { + "event_id": "d3-d2dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:16:12.513046+00:00" + }, + { + "event_id": "d3-d2dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-21T21:16:26.836862+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/test.sh b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d3-d2dep-paymentfailure-50-03-medium_ttd480m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/environment/Dockerfile b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/environment/docker-compose.yaml b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/check_prediction.py b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubric.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubric.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/solve.py b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/solve.sh b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/check_prediction.py b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/expected.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c70e133782e60afecdddba797b9d87001e2ee31a --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d3-d2dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-21T21:16:26.836862+00:00" + }, + { + "event_id": "d3-d2dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-21T18:45:50.326565+00:00" + }, + { + "event_id": "d3-d2dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:16:12.513046+00:00" + }, + { + "event_id": "d3-d2dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-21T20:46:18.899501+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentFailure-10%.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..c57e9a69a8cf2d53e24ac6d523604764f36450e1 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentFailure-10%.json @@ -0,0 +1,171 @@ +{ + "incident_time": "2026-04-21T20:16:12.513046+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='payment',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for the payment service's error spans. Before the incident this was zero; after the paymentFailure flag activates, ~10% of oteldemo.PaymentService/Charge calls throw 'Payment request failed', creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above baseline. This is about 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name='checkout',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived call counter for checkout's client-side view of payment charge errors. The checkout service's chargeCard call to the payment service now returns errors ('could not charge the card'), producing new STATUS_CODE_ERROR spans that were absent before the incident.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the clear onset of the error-rate spike. This is ~10 minutes after the incident injection at 20:16, consistent with the 5m rate window smoothing delay." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration counter for payment service error spans. This metric was zero before the incident and appeared after the paymentFailure flag activated, tracking the duration of failed payment charge operations.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it first rises to ~0.00417, marking the initial spike above the zero baseline. This is approximately 10 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to register new error spans." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name='payment',span_name='oteldemo.PaymentService/Charge',status_code='STATUS_CODE_ERROR'}[5m]))", + "description": "Span-derived duration sum for payment service error spans. Tracks cumulative duration of failed charge operations; was zero before the incident and spiked after the paymentFailure flag caused 10% of charges to throw errors.", + "onset_utc": "2026-04-21 20:26:00 UTC", + "onset_offset_seconds": 587, + "onset_reasoning": "The metric is flat at 0 from the start through 20:25. At 20:26 it jumps to ~0.0039, marking the first clear spike above the zero baseline after the incident time." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "incremental" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_count{service_name=\"payment\",v8js_gc_type=\"incremental\"}[5m])", + "description": "Payment service V8 incremental GC invocation rate jumped from 0 to ~1.33/sec. The 10% payment failure rate causes charge.js to throw Error objects with stack traces, generating heap garbage that triggers V8's incremental garbage collector — which was previously inactive under normal steady-state load.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "The metric is flat at 0 from the start through 20:23. At 20:24 it jumps to 0.2555, marking the first non-zero value and the clear start of the spike. This is about 8 minutes after the incident injection at 20:16, consistent with the 5m rate window needing time to accumulate counts." + } + ] + }, + { + "metric_family": "v8js_gc_duration_seconds", + "signal_layer": "meta", + "defining_labels": { + "service_name": "payment", + "v8js_gc_type": "major" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(v8js_gc_duration_seconds_sum{service_name=\"payment\",v8js_gc_type=\"major\"}[5m])", + "description": "Payment service V8 major GC time increased ~7% (from 0.0096 to 0.0103 sec/sec). The error-path Error objects and stack traces created by the paymentFailure flag increase heap pressure, causing V8 major GC cycles to take longer.", + "onset_utc": "2026-04-21 20:24:00 UTC", + "onset_offset_seconds": 467, + "onset_reasoning": "Pre-incident baseline is ~0.00964. The value at 20:23 (0.00963615) is still within baseline noise. At 20:24 (0.0096584) the value jumps noticeably above baseline, and continues rising sharply through 20:25–20:28 until leveling off around 0.01029. This is the first clear departure from the stable ~0.00964 baseline." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:24:15 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "dbO3sZ0Br_RFnSwRCZMG", + "@timestamp": "20:24:15.551" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:24:15 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "ALO3sZ0Br_RFnSwRHpRq", + "@timestamp": "20:24:15.582" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:24:15 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "d019350aa42d05cd4c5a84b38a44cc18", + "@timestamp": "20:24:15", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentFailure-50%.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..33e11d13dc4b249e336480fe9f557ef244c38125 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentFailure-50%.json @@ -0,0 +1,252 @@ +{ + "incident_time": "2026-04-21T20:46:18.899501+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Cumulative duration of payment Charge error spans. Each failed charge adds ~1ms of error span duration. Sum grew from 36.53ms to 40.51ms (+3.98ms) as 5 new payment failures accumulated.", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "The metric is at zero from 20:38 through 20:52 (covering the incident time). At 20:53 it rises to ~0.00343 and continues climbing to ~0.0166 by 20:56, representing a clear spike above the zero baseline. 20:53 is the first timestamp after the incident where the value reappears and begins the sustained increase." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Count of payment Charge error span durations recorded. Mirrors the calls_total counter, tracking how many error duration observations were recorded for the payment Charge RPC. Counter grew from 32 to 37 (+5).", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline shows low-level activity (~0.004) that drops to zero around 20:38. After the incident at 20:46, the metric remains zero until 20:53 when it reappears at 0.0041667 and then rapidly spikes to 0.0208 by 20:56, well above the pre-incident baseline of ~0.004. This marks the clear onset of the error rate spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, creating new STATUS_CODE_ERROR spans that did not exist before the incident. Counter grew from 32 to 37 (+5) in the 10 minutes after the flag was set.", + "onset_utc": "2026-04-21 20:55:00 UTC", + "onset_offset_seconds": 521, + "onset_reasoning": "Pre-incident baseline was ~0.004. After the incident at 20:46, the metric remains at 0 until 20:53-20:54 where it returns to baseline level (~0.004). At 20:55 it jumps to 0.0125 (3x baseline), then continues rising to 0.0208 at 20:56, clearly spiking above the pre-incident baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC Charge calls to the payment service started returning UNKNOWN (status 2) errors when the payment service threw 'Payment request failed' errors at 50% rate", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.00417 (with occasional zeros/doubles). The metric dropped to zero around 20:38 and stayed zero through the incident. At 20:53 it resumes at baseline, then spikes to 0.0208 by 20:56 — roughly 5x the baseline. 20:53 is the first timestamp after the incident where the metric begins its upward trajectory toward the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked as payment failures cascaded through checkout to the frontend", + "onset_utc": "2026-04-21 20:52:00 UTC", + "onset_offset_seconds": 341, + "onset_reasoning": "Pre-incident baseline was ~0.004 req/s with occasional zeros. After the incident at 20:46, the metric stays at 0 until 20:52 when it reappears and then ramps up to 0.0167 (4x baseline) by 20:56-20:58, indicating the start of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC INTERNAL errors spiked as payment charge failures propagated through the checkout service, causing orders to fail with codes.Internal", + "onset_utc": "2026-04-21 20:53:00 UTC", + "onset_offset_seconds": 401, + "onset_reasoning": "Pre-incident baseline was ~0.004 with gaps of zero. After the incident at 20:46, the series stays at 0 until 20:53 when it reappears and then climbs to 0.0125–0.0208 (3–5x the baseline), marking the clear start of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "fbPPsZ0Br_RFnSwRut_P", + "@timestamp": "20:51:13.267" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "kLPRsZ0Br_RFnSwRuuXG", + "@timestamp": "20:53:24.385" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "q7PSsZ0Br_RFnSwRIeb5", + "@timestamp": "20:53:51.416" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "CbPSsZ0Br_RFnSwRg-i3", + "@timestamp": "20:54:16.372" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "QLPSsZ0Br_RFnSwRiejx", + "@timestamp": "20:54:18.043" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:51:13 and 20:54:18 UTC, 5 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 17–24ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "0LPPsZ0Br_RFnSwRzd-c", + "@timestamp": "20:51:13.288" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "57PRsZ0Br_RFnSwRzeXq", + "@timestamp": "20:53:24.406" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "IbPSsZ0Br_RFnSwRN-eX", + "@timestamp": "20:53:51.434" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "9rPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:16.391" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "-LPSsZ0Br_RFnSwRmeh0", + "@timestamp": "20:54:18.068" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:51:13 and 20:54:17 UTC, 5 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "83be1af02c90c1b8dcece1be003c4e6a", + "@timestamp": "20:51:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "5994d961af0890def86006f8e18d007e", + "@timestamp": "20:53:24", + "user_action": "user_checkout_single" + }, + { + "traceID": "c1792a7f3df0958d0d552c508cbd5f2e", + "@timestamp": "20:53:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "4740fed768edb3e9db16fdb10499db81", + "@timestamp": "20:54:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "7a114aa4d37cbde12f912c6a433e06cd", + "@timestamp": "20:54:17", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentUnreachable-on.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..19dc58a7e3a067961460b050c8aaa58d9056f748 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-paymentUnreachable-on.json @@ -0,0 +1,250 @@ +{ + "incident_time": "2026-04-21T21:16:26.836862+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_usage_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container total CPU usage rate spiked from ~2.3M to ~7.9M nanoseconds/sec (~245% increase) due to repeated gRPC dial attempts and DNS lookups to the unreachable badAddress:50051", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 2.0e6 and 2.7e6. After the incident at 21:16, the first two minutes (21:17–21:18) remain within that normal range (~2.28e6, ~2.32e6). At 21:19 the value jumps to 2.80e6, clearly breaking above the prior ceiling, and continues climbing steadily to ~5.86e6 by 21:36. This marks the clear onset of the sustained spike." + } + ] + }, + { + "metric_family": "container_cpu_usage_usermode_nanoseconds", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(container_cpu_usage_usermode_nanoseconds_total{container_name=\"checkout\"}[5m])", + "description": "Checkout container usermode CPU usage rate spiked from ~1.9M to ~6.8M nanoseconds/sec (~262% increase), reflecting the application-level gRPC client retry logic consuming CPU as it repeatedly tries to reach the bogus payment address", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 1.55e6 and 2.05e6. After the incident at 21:16, the value at 21:19 (2.30e6) is the first point that decisively breaks above the prior baseline ceiling and the series continues climbing from there without returning." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "propagation", + "defining_labels": { + "error_type": "ArgumentOutOfRangeException", + "job": "opentelemetry-demo/accounting" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(dotnet_exceptions_total{job=\"opentelemetry-demo/accounting\", error_type=\"ArgumentOutOfRangeException\"}[5m])", + "description": "Accounting service ArgumentOutOfRangeException rate collapsed from ~0.049/s to 0. These exceptions were thrown during order-message processing; with no new orders arriving via Kafka, the code path that triggers them is no longer exercised.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "The pre-incident pattern shows low-level oscillating exception activity (values typically 0.0125–0.0625). After the incident at 21:16, the signal continues briefly at ~0.0125 through 21:19. At 21:20 the value drops to 0 and remains flat at 0 for the rest of the series, never recovering. The last non-trivial value is at 21:19, marking the onset of collapse." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend /api/checkout requests returning HTTP 500 increased because all checkout attempts now fail. Previously only a fraction failed (from paymentFailure flag); now 100% fail due to paymentUnreachable.", + "onset_utc": "2026-04-21 21:19:00 UTC", + "onset_offset_seconds": 153, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.021. After the incident at 21:16, the value at 21:19 (0.025) is the first timestamp that clearly rises above the prior baseline range and stays elevated (0.025-0.037) for the remainder of the series." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "success": "true", + "type": "span" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\",type=\"span\",success=\"true\"}[5m])", + "description": "Fraud-detection OTLP exporter exported span count collapsed ~82%. With near-zero spans being processed, the OTLP exporter has almost nothing to export.", + "onset_utc": "2026-04-21 21:15:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "Pre-incident the metric oscillates with values typically between 0.008-0.042. At 21:15 the value is 0.0125, then at 21:16 (incident time) it drops to 0. After that the signal is nearly dead — brief tiny blips of 0.00417 but predominantly zero. The last timestamp showing the pre-incident active pattern is 21:15, after which the signal collapses." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-21T21:17:14.661Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 386 21 27 26 \"-\" \"python-requests/2.32.5\" \"e88fdae8-787a-918f-8a1c-4a8969f54782\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:50998 172.18.0.29:8080 172.18.0.28:42912 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "1LTnsZ0Br_RFnSwRjicg", + "@timestamp": "21:17:14.661" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tbTqsZ0Br_RFnSwRSjD6", + "@timestamp": "21:20:14.561" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "3LTssZ0Br_RFnSwRCjW4", + "@timestamp": "21:22:08.876" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "dbTssZ0Br_RFnSwRHzba", + "@timestamp": "21:22:14.240" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "0rTssZ0Br_RFnSwROzYu", + "@timestamp": "21:22:21.393" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "tLTtsZ0Br_RFnSwRVDl7", + "@timestamp": "21:23:33.539" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "jLTusZ0Br_RFnSwROTxp", + "@timestamp": "21:24:32.477" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "KbTusZ0Br_RFnSwRST0M", + "@timestamp": "21:24:36.481" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ALTusZ0Br_RFnSwRxz-k", + "@timestamp": "21:25:09.078" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "g7TvsZ0Br_RFnSwRMUAg", + "@timestamp": "21:25:35.407" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:17:14 and 21:25:35 UTC, 10 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "f9aa06a16e48e546476c4b8bdea1bcef", + "@timestamp": "21:17:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0014246b6f2375b939d58268e602716a", + "@timestamp": "21:20:14", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cb3f8b2e70f2f44328339dd4584bb0a4", + "@timestamp": "21:22:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e9f1860b4d10ef0cf1e195f4a833f507", + "@timestamp": "21:22:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "a4673653b956af68b29c2a8e9346a4cf", + "@timestamp": "21:22:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "57dab6aa93b250fe545258e0208e72c0", + "@timestamp": "21:23:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "21385404497a1f1ced3058d99135cd04", + "@timestamp": "21:24:32", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ca1246629c500c8ac50c87122774392", + "@timestamp": "21:24:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "832e60599ed2c49718c1e250a78ad744", + "@timestamp": "21:25:09", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0234e130343ef5567ea626f40330e97", + "@timestamp": "21:25:35", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-productCatalogFailure-on.json b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..97882822e5db433201b078d7409877b1ff2cb560 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/rubrics/d3-d2dep-productCatalogFailure-on.json @@ -0,0 +1,502 @@ +{ + "incident_time": "2026-04-21T18:45:50.326565+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on product-catalog GetProduct, caused by the productCatalogFailure flag returning an error for product OLJCESPC7Z", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "The metric is flat at 0 from 18:25 through 18:47. At 18:48 it jumps to 0.00416667, the first non-zero value, marking the clear start of the spike in rpc_server_duration error rate for GetProduct with status code 13." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC client-side Internal errors from checkout calling GetProduct on product-catalog for OLJCESPC7Z", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "The metric is flat at 0 from the start through 18:49. At 18:50 it first rises to 0.00417, marking the initial spike above the zero baseline. This is ~4 minutes after the incident time (18:45:50), consistent with the 5m rate window needing time to register new errors." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"GET\",status=\"500\",target=\"/api/products/OLJCESPC7Z\"}[5m])", + "description": "Frontend HTTP 500 errors on product page for OLJCESPC7Z, directly caused by GetProduct returning Internal error", + "onset_utc": "2026-04-21 18:48:00 UTC", + "onset_offset_seconds": 129, + "onset_reasoning": "Baseline is steady at 0 for all pre-incident samples. After the incident at 18:45:50, the first non-zero value appears at 18:48:00 (0.00417), marking the clear start of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for productCatalogFailure flag evaluating to 'on' variant, confirming the flag is active and being evaluated", + "onset_utc": "2026-04-21 18:47:00 UTC", + "onset_offset_seconds": 69, + "onset_reasoning": "The metric is flat at 0 before the incident. The first non-zero value appears at 18:47:00 UTC (0.00416667), which is the first timestamp after the incident time where the feature flag impression rate spikes above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "gRPC server-side Internal errors on checkout PlaceOrder, cascading from GetProduct failure when OLJCESPC7Z is in the cart", + "onset_utc": "2026-04-21 18:50:00 UTC", + "onset_offset_seconds": 249, + "onset_reasoning": "Pre-incident baseline is consistently 0. After the incident at 18:45:50 UTC, the metric remains at 0 until 18:50:00 UTC when it first rises to 0.00416667, marking the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:46:14 and 18:55:28 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "LLJdsZ0Br_RFnSwRT3EZ", + "@timestamp": "18:46:14.782" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JesZ0Br_RFnSwRv3a6", + "@timestamp": "18:47:49.565" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "d7JfsZ0Br_RFnSwRW3j9", + "@timestamp": "18:48:29.381" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JfsZ0Br_RFnSwRhnj2", + "@timestamp": "18:48:40.180" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "ibJgsZ0Br_RFnSwRSnxJ", + "@timestamp": "18:49:30.408" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "v7JhsZ0Br_RFnSwRkYAe", + "@timestamp": "18:50:54.555" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "GrJhsZ0Br_RFnSwRmoFR", + "@timestamp": "18:50:56.889" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5bJhsZ0Br_RFnSwRyYEt", + "@timestamp": "18:51:08.638" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "DLJisZ0Br_RFnSwRKYN6", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "47JisZ0Br_RFnSwRYIM2", + "@timestamp": "18:51:46.947" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "cbJisZ0Br_RFnSwRf4Ry", + "@timestamp": "18:51:54.871" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "hrJjsZ0Br_RFnSwRRIYk", + "@timestamp": "18:52:45.589" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "BbJjsZ0Br_RFnSwRtYh5", + "@timestamp": "18:53:14.239" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJksZ0Br_RFnSwRHYng", + "@timestamp": "18:53:41.203" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "_7JksZ0Br_RFnSwR6os7", + "@timestamp": "18:54:33.613" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "K7JksZ0Br_RFnSwR_Iyy", + "@timestamp": "18:54:37.942" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "WLJlsZ0Br_RFnSwRwI4C", + "@timestamp": "18:55:28.593" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:52:08 and 18:54:30 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "FbJisZ0Br_RFnSwRsoU8", + "@timestamp": "18:52:08.144" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "m7JjsZ0Br_RFnSwRToaj", + "@timestamp": "18:52:47.716" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "gbJjsZ0Br_RFnSwRjodd", + "@timestamp": "18:53:04.229" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "TLJjsZ0Br_RFnSwR1Ii8", + "@timestamp": "18:53:22.656" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "77JksZ0Br_RFnSwR3ouD", + "@timestamp": "18:54:30.987" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 18:48:40 and 18:50:54 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-21", + "_id": "AbJfsZ0Br_RFnSwRhnn2", + "@timestamp": "18:48:40.201" + }, + { + "_index": "otel-logs-2026-04-21", + "_id": "5rJhsZ0Br_RFnSwRlYAH", + "@timestamp": "18:50:54.631" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:43:52 and 18:55:28 UTC, 19 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (14), user_add_to_cart (3). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "68564af3a0eb62faba74572f3a143e70", + "@timestamp": "18:55:28", + "user_action": "user_browse_product" + }, + { + "traceID": "3427c5998eb37eae32f7c1471a9f8ab7", + "@timestamp": "18:54:37", + "user_action": "user_browse_product" + }, + { + "traceID": "dfa0da3092e31477e7d0246f7fa9537f", + "@timestamp": "18:54:33", + "user_action": "user_browse_product" + }, + { + "traceID": "daa5ca747f878529c3c82a01426841c5", + "@timestamp": "18:54:03" + }, + { + "traceID": "326c14609dfd06f6ef2e6c44e7f54ecc", + "@timestamp": "18:53:41", + "user_action": "user_browse_product" + }, + { + "traceID": "a86047eecc2d36cb4dee518616518558", + "@timestamp": "18:53:14", + "user_action": "user_browse_product" + }, + { + "traceID": "328dd5788bceb5ff9a0f29b2ef651826", + "@timestamp": "18:52:45", + "user_action": "user_browse_product" + }, + { + "traceID": "9243a2892c9af0d10b073d1bd3b75cbc", + "@timestamp": "18:51:54", + "user_action": "user_browse_product" + }, + { + "traceID": "15167321bc7adf5647c499a596e8964c", + "@timestamp": "18:51:46", + "user_action": "user_browse_product" + }, + { + "traceID": "632ee2e08827c877142ba4bda0b46575", + "@timestamp": "18:51:33", + "user_action": "user_browse_product" + }, + { + "traceID": "36e829e8eda77382eb885664bbf16def", + "@timestamp": "18:51:08", + "user_action": "user_browse_product" + }, + { + "traceID": "41a9e65da93924611af302c60008bcb2", + "@timestamp": "18:50:56", + "user_action": "user_browse_product" + }, + { + "traceID": "fa9c5a9b2f01adb940faa65196cf5e62", + "@timestamp": "18:50:54", + "user_action": "user_add_to_cart" + }, + { + "traceID": "35f7e372d9b99c9fff7e68a6537bbe20", + "@timestamp": "18:49:30", + "user_action": "user_browse_product" + }, + { + "traceID": "300a4c577c651cdf98e278777d35fdd5", + "@timestamp": "18:48:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "bfc200ad2feb05e6cac9d4e323d40a6b", + "@timestamp": "18:48:29", + "user_action": "user_browse_product" + }, + { + "traceID": "37a4871f0337aa27bce4011de87a1f48", + "@timestamp": "18:47:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "c71c0cd382852efb18b12063c8c10169", + "@timestamp": "18:46:14", + "user_action": "user_browse_product" + }, + { + "traceID": "653c4e303ecc718e11050a51440816e2", + "@timestamp": "18:43:52" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:52:08 and 18:54:30 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "518b724d0c0727813d339ba953be0718", + "@timestamp": "18:54:30", + "user_action": "user_get_recommendations" + }, + { + "traceID": "bffe89fd7631f67293392cb81a551480", + "@timestamp": "18:53:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e1c78fffd37321de897b0f8c6e27fb2b", + "@timestamp": "18:53:04", + "user_action": "user_get_recommendations" + }, + { + "traceID": "03e9e41f84e9aad4fc949325b0147d00", + "@timestamp": "18:52:47", + "user_action": "user_get_recommendations" + }, + { + "traceID": "1bf30cef2b22ebe6b917ac2039c7a2a6", + "@timestamp": "18:52:08", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 18:48:40 and 18:50:54 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "18d49ea8ede7b5b37f28b52265cf3340", + "@timestamp": "18:50:54", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a5784c77b5c101811d8971344b6745b1", + "@timestamp": "18:48:40", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/test.sh b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d3-d2dep-paymentunreachable-on-02-medium_ttd480m_period_previous-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/environment/Dockerfile b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/environment/docker-compose.yaml b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/check_prediction.py b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/solve.py b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/solve.sh b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/check_prediction.py b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/expected.json b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/test.sh b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..05ed53a2cdd869487cab917ac34047c44dd790e3 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-21T14:14:18.261797+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d3-ic1-imageSlowLoad-on.json b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d3-ic1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..05ed53a2cdd869487cab917ac34047c44dd790e3 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d3-ic1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-21T14:14:18.261797+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..019e9c5b22ae1518b1a087471d1d4e338be1537e --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d3-ic1-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-21T14:14:18.261797+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d3-ic1-imageSlowLoad-on.json b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d3-ic1-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..05ed53a2cdd869487cab917ac34047c44dd790e3 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d3-ic1-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-21T14:14:18.261797+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d3-ic1-imageslowload-on-univ00-universal_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/rubric.json b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/rubrics/d5-ic2-adFailure-on.json b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/solve.py b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/solve.sh b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/expected.json b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..dcb516a3468bd032038c446f59eeb506855a0a2d --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d5-ic2-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-23T14:26:55.696106+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/rubrics/d5-ic2-adFailure-on.json b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/test.sh b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d4-cc2-admanualgc-on-01-hard_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/environment/Dockerfile b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/environment/docker-compose.yaml b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/check_prediction.py b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/solve.py b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/solve.sh b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/check_prediction.py b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/expected.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/test.sh b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/environment/Dockerfile b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/environment/docker-compose.yaml b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/check_prediction.py b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubric.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7db86e578213a88b97fea945d9a0c0a8ac87bb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubric.json @@ -0,0 +1,301 @@ +{ + "incident_time": "2026-04-22T20:52:46.740910+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call rate for payment service's Charge RPC with error status. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, producing new STATUS_CODE_ERROR spans on the payment service.", + "onset_utc": "2026-04-22 20:55:00 UTC", + "onset_offset_seconds": 133, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors (~0.004 or 0) with many zero values. After the incident at 20:52:46, the metric jumps to 0.00833333 at 20:55:00 — roughly 2x the previous sporadic baseline — and sustains elevated values (0.008–0.02) from that point onward, indicating the clear start of the error spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_service": "oteldemo.PaymentService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_service=\"oteldemo.PaymentService\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC client calls to PaymentService/Charge returning Unknown (code 2) status spiked as the payment service throws errors when the paymentFailure flag triggers", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline oscillates between 0 and ~0.00417. After the incident at 20:52:46, the value at 20:54 jumps to 0.00833, which is 2x the baseline, and continues rising to a peak of ~0.0208 at 21:00. This is the first timestamp after the incident where the metric clearly exceeds the pre-incident range." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout requests returning HTTP 500 increased as the paymentFailure flag causes ~50% of payment charges to throw errors, which propagate through checkout as gRPC Internal errors and surface as HTTP 500 responses", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (~0.004) interspersed with zeros. After the incident at 20:52:46, the first post-incident nonzero value at 20:54 is 0.00833, which is ~2x the baseline sporadic value, and it sustains and climbs further (0.0125, 0.0167, 0.0208), confirming a clear spike onset at 20:54." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag with variant '50%' stepped from 2 to 3 at incident time, recording the flag configuration change that activated the 50% payment failure rate", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "The metric holds steady at 2 from 20:32 through 20:53. At 20:54 it jumps to 3 and remains there, which is the first timestamp after the incident time (20:52:46) showing a clear rise above the baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_service": "oteldemo.CheckoutService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.CheckoutService\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout gRPC server calls returning Internal (code 13) status increased as payment failures propagate through checkout's PlaceOrder handler which returns codes.Internal when chargeCard fails", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (0 to ~0.00417). After the incident at 20:52:46, the metric jumps to 0.00833 at 20:54 — double the previous max baseline value — and continues rising to a peak of ~0.0208 at 21:00, confirming a clear spike. 20:54 is the first post-incident timestamp with a sustained elevated value." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "Ccb3tp0Br_RFnSwRwgM9", + "@timestamp": "20:53:03.061" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "A8b3tp0Br_RFnSwR4QTz", + "@timestamp": "20:53:11.157" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OMb6tp0Br_RFnSwRkQw4", + "@timestamp": "20:56:07.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcb6tp0Br_RFnSwR6w2J", + "@timestamp": "20:56:30.579" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "jcb7tp0Br_RFnSwRHg5O", + "@timestamp": "20:56:43.267" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "zMb8tp0Br_RFnSwRJxHB", + "@timestamp": "20:57:51.593" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "tcb8tp0Br_RFnSwRyxPZ", + "@timestamp": "20:58:33.292" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "TMb_tp0Br_RFnSwRLRpT", + "@timestamp": "21:01:09.017" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "osYAt50Br_RFnSwREBxE", + "@timestamp": "21:02:07.788" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–43ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tsb3tp0Br_RFnSwR1gNn", + "@timestamp": "20:53:03.104" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "iMb3tp0Br_RFnSwR9QTa", + "@timestamp": "20:53:11.181" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "08b6tp0Br_RFnSwRpQza", + "@timestamp": "20:56:07.671" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Pcb6tp0Br_RFnSwR_w7i", + "@timestamp": "20:56:30.622" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "CMb7tp0Br_RFnSwRMg_c", + "@timestamp": "20:56:43.293" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "UMb8tp0Br_RFnSwRPBLk", + "@timestamp": "20:57:51.613" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Gcb8tp0Br_RFnSwR4RQw", + "@timestamp": "20:58:33.317" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "icb_tp0Br_RFnSwRPhry", + "@timestamp": "21:01:09.047" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "VsYAt50Br_RFnSwRJR2k", + "@timestamp": "21:02:07.828" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:53:02 and 21:02:07 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "66b9ba801adf9f9f422434a778f79537", + "@timestamp": "20:53:02", + "user_action": "user_checkout_multi" + }, + { + "traceID": "72837353452f8a345bec058d3d020268", + "@timestamp": "20:53:11", + "user_action": "user_checkout_single" + }, + { + "traceID": "f255f946901777cd31f6d12a5f098a9e", + "@timestamp": "20:56:07", + "user_action": "user_checkout_single" + }, + { + "traceID": "f45d35ba65bccb4c4978380da5646dbc", + "@timestamp": "20:56:30", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b206613c795a05a3544ea6896b7691b", + "@timestamp": "20:56:43", + "user_action": "user_checkout_single" + }, + { + "traceID": "ad89464077ece735dd371b3d222a868d", + "@timestamp": "20:57:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "f394303704028931b06bfd39a4597301", + "@timestamp": "20:58:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "e021d85134fb82acc1f87a9e52abaf43", + "@timestamp": "21:01:08", + "user_action": "user_checkout_single" + }, + { + "traceID": "804e3624540aa57a66685981d6aa655a", + "@timestamp": "21:02:07", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..e55cb50e5ea8db42bed372710d0f6b475b1f759c --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json @@ -0,0 +1,200 @@ +{ + "incident_time": "2026-04-22T20:22:41.236522+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the payment service's Charge RPC. Was zero before the incident; the paymentFailure flag causes ~10% of charge calls to throw, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram count for payment Charge errors. Was zero before the incident; each failed charge produces a duration sample in this histogram.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:28. The first non-zero value appears at 20:29 (0.00416667), which is about 6 minutes after the incident time. This is the clear onset of the spike above the zero baseline." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration sum for payment Charge errors. Was zero before the incident; tracks cumulative latency of failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00426, which is the first non-zero value after the incident time (20:22:41). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram buckets for payment Charge errors. Was zero before the incident; populates latency distribution buckets for failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The baseline is 0 throughout the pre-incident period. After the incident at 20:22:41 UTC, the metric remains at 0 until 20:29:00 UTC when it first spikes to 0.0708333, clearly rising above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": "2026-04-22 20:24:00 UTC", + "onset_offset_seconds": 78, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:23. At 20:24 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"checkout\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the checkout service's client-side PaymentService/Charge span. Was zero before the incident; errors from the payment service propagate as gRPC errors on the checkout side.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:27:53 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "IsXgtp0Br_RFnSwRubU5", + "@timestamp": "20:27:53.167" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:27:53 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "ksXgtp0Br_RFnSwRy7W0", + "@timestamp": "20:27:53.198" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:27:53 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2de5b0fee49445b07e09b4338ca9f884", + "@timestamp": "20:27:53", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7db86e578213a88b97fea945d9a0c0a8ac87bb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json @@ -0,0 +1,301 @@ +{ + "incident_time": "2026-04-22T20:52:46.740910+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call rate for payment service's Charge RPC with error status. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, producing new STATUS_CODE_ERROR spans on the payment service.", + "onset_utc": "2026-04-22 20:55:00 UTC", + "onset_offset_seconds": 133, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors (~0.004 or 0) with many zero values. After the incident at 20:52:46, the metric jumps to 0.00833333 at 20:55:00 — roughly 2x the previous sporadic baseline — and sustains elevated values (0.008–0.02) from that point onward, indicating the clear start of the error spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_service": "oteldemo.PaymentService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_service=\"oteldemo.PaymentService\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC client calls to PaymentService/Charge returning Unknown (code 2) status spiked as the payment service throws errors when the paymentFailure flag triggers", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline oscillates between 0 and ~0.00417. After the incident at 20:52:46, the value at 20:54 jumps to 0.00833, which is 2x the baseline, and continues rising to a peak of ~0.0208 at 21:00. This is the first timestamp after the incident where the metric clearly exceeds the pre-incident range." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout requests returning HTTP 500 increased as the paymentFailure flag causes ~50% of payment charges to throw errors, which propagate through checkout as gRPC Internal errors and surface as HTTP 500 responses", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (~0.004) interspersed with zeros. After the incident at 20:52:46, the first post-incident nonzero value at 20:54 is 0.00833, which is ~2x the baseline sporadic value, and it sustains and climbs further (0.0125, 0.0167, 0.0208), confirming a clear spike onset at 20:54." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag with variant '50%' stepped from 2 to 3 at incident time, recording the flag configuration change that activated the 50% payment failure rate", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "The metric holds steady at 2 from 20:32 through 20:53. At 20:54 it jumps to 3 and remains there, which is the first timestamp after the incident time (20:52:46) showing a clear rise above the baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_service": "oteldemo.CheckoutService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.CheckoutService\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout gRPC server calls returning Internal (code 13) status increased as payment failures propagate through checkout's PlaceOrder handler which returns codes.Internal when chargeCard fails", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (0 to ~0.00417). After the incident at 20:52:46, the metric jumps to 0.00833 at 20:54 — double the previous max baseline value — and continues rising to a peak of ~0.0208 at 21:00, confirming a clear spike. 20:54 is the first post-incident timestamp with a sustained elevated value." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "Ccb3tp0Br_RFnSwRwgM9", + "@timestamp": "20:53:03.061" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "A8b3tp0Br_RFnSwR4QTz", + "@timestamp": "20:53:11.157" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OMb6tp0Br_RFnSwRkQw4", + "@timestamp": "20:56:07.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcb6tp0Br_RFnSwR6w2J", + "@timestamp": "20:56:30.579" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "jcb7tp0Br_RFnSwRHg5O", + "@timestamp": "20:56:43.267" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "zMb8tp0Br_RFnSwRJxHB", + "@timestamp": "20:57:51.593" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "tcb8tp0Br_RFnSwRyxPZ", + "@timestamp": "20:58:33.292" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "TMb_tp0Br_RFnSwRLRpT", + "@timestamp": "21:01:09.017" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "osYAt50Br_RFnSwREBxE", + "@timestamp": "21:02:07.788" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–43ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tsb3tp0Br_RFnSwR1gNn", + "@timestamp": "20:53:03.104" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "iMb3tp0Br_RFnSwR9QTa", + "@timestamp": "20:53:11.181" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "08b6tp0Br_RFnSwRpQza", + "@timestamp": "20:56:07.671" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Pcb6tp0Br_RFnSwR_w7i", + "@timestamp": "20:56:30.622" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "CMb7tp0Br_RFnSwRMg_c", + "@timestamp": "20:56:43.293" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "UMb8tp0Br_RFnSwRPBLk", + "@timestamp": "20:57:51.613" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Gcb8tp0Br_RFnSwR4RQw", + "@timestamp": "20:58:33.317" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "icb_tp0Br_RFnSwRPhry", + "@timestamp": "21:01:09.047" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "VsYAt50Br_RFnSwRJR2k", + "@timestamp": "21:02:07.828" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:53:02 and 21:02:07 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "66b9ba801adf9f9f422434a778f79537", + "@timestamp": "20:53:02", + "user_action": "user_checkout_multi" + }, + { + "traceID": "72837353452f8a345bec058d3d020268", + "@timestamp": "20:53:11", + "user_action": "user_checkout_single" + }, + { + "traceID": "f255f946901777cd31f6d12a5f098a9e", + "@timestamp": "20:56:07", + "user_action": "user_checkout_single" + }, + { + "traceID": "f45d35ba65bccb4c4978380da5646dbc", + "@timestamp": "20:56:30", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b206613c795a05a3544ea6896b7691b", + "@timestamp": "20:56:43", + "user_action": "user_checkout_single" + }, + { + "traceID": "ad89464077ece735dd371b3d222a868d", + "@timestamp": "20:57:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "f394303704028931b06bfd39a4597301", + "@timestamp": "20:58:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "e021d85134fb82acc1f87a9e52abaf43", + "@timestamp": "21:01:08", + "user_action": "user_checkout_single" + }, + { + "traceID": "804e3624540aa57a66685981d6aa655a", + "@timestamp": "21:02:07", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cffa8510af04230dcb573fbf0b4f7aa4adf8d972 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json @@ -0,0 +1,357 @@ +{ + "incident_time": "2026-04-22T21:22:52.483960+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "0", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"0\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "Successful (OK) gRPC Charge calls from checkout to payment dropped to zero because the gRPC client is directed at badAddress:50051 which fails DNS resolution", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "Pre-incident, the metric oscillates between ~0.004 and ~0.017 with typical values around 0.008. After the incident at 21:22:52, the value at 21:23 is 0.00417 (still within normal range), then 21:24 shows 0.00417 as the last non-zero reading. From 21:25 onward the signal drops to zero and never recovers. The onset is 21:24 — the last timestamp showing pre-incident activity before the collapse." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "14", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"14\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "New gRPC UNAVAILABLE (code 14) errors appeared on checkout's client calls to PaymentService/Charge — the gRPC dial to badAddress:50051 fails with DNS resolution error", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric is flat at 0 from 21:02 through 21:23 (including the incident marker). At 21:24 it jumps to 0.00417, the first non-zero value, and continues rising steadily thereafter. This is the clear onset of the spike." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "propagation", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate", + "description": "Kafka consumer byte consumption rate dropped to zero because no order records are being produced to the orders topic, leaving the fraud-detection consumer with nothing to consume", + "onset_utc": "2026-04-22 21:21:00 UTC", + "onset_offset_seconds": -112, + "onset_reasoning": "Pre-incident pattern shows periodic non-zero values every 1-3 minutes (9.25, 9.54, 5.48, 8.7, 4.08, 4.35, 4.51, 4.27, 4.95). The last non-zero value is at 21:21 (4.9464). From 21:22 onward the signal is permanently zero, aligning with the incident at 21:22:52. This is the last active timestamp before the collapse." + } + ] + }, + { + "metric_family": "app_confirmation_counter", + "signal_layer": "symptom", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_confirmation_counter_total[5m])", + "description": "Checkout order confirmation rate dropped to zero because every checkout fails at the payment step, so no order confirmation emails are sent", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low but non-zero activity (oscillating around 0.004-0.017) before the incident. At 21:24 the value is 0.00416642, and from 21:25 onward it drops to zero permanently. The last non-trivial value is at 21:24, marking the final moment the pre-incident pattern is still active before the signal collapses." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "type": "log" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\", type=\"log\"}[5m])", + "description": "OTLP exporter record counter for logs exported by the fraud-detection service. Collapsed to zero because fraud-detection produces no order-processing logs when no orders arrive via Kafka.", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low-level periodic activity (oscillating roughly 0.004–0.017) before the incident. At 21:24 the value is 0.00416667, and from 21:25 onward it drops to 0 permanently. So 21:24 is the last timestamp with non-zero activity before the signal collapses, aligning closely with the incident time of 21:22:52." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-22T21:22:56.660Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 372 21 37 36 \"-\" \"python-requests/2.32.5\" \"39765a6c-ead4-9254-b089-6d267091fe68\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:60672 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "zMYTt50Br_RFnSwRIFmm", + "@timestamp": "21:22:56.660" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "q8YTt50Br_RFnSwRuVsu", + "@timestamp": "21:23:36.192" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OsYTt50Br_RFnSwR2Fxc", + "@timestamp": "21:23:43.528" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYUt50Br_RFnSwRt18x", + "@timestamp": "21:24:40.599" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "JMYVt50Br_RFnSwRU2G7", + "@timestamp": "21:25:21.132" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "b8YVt50Br_RFnSwRW2GB", + "@timestamp": "21:25:23.001" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cYVt50Br_RFnSwR6GM2", + "@timestamp": "21:25:59.000" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "bMYWt50Br_RFnSwROmVG", + "@timestamp": "21:26:19.473" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "58YWt50Br_RFnSwRv2Yb", + "@timestamp": "21:26:53.885" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYWt50Br_RFnSwRxmfp", + "@timestamp": "21:26:55.839" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "mMYWt50Br_RFnSwR1meH", + "@timestamp": "21:26:59.477" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "NMYXt50Br_RFnSwRfmmP", + "@timestamp": "21:27:43.350" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "FMYXt50Br_RFnSwRoWqt", + "@timestamp": "21:27:51.861" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "f8YXt50Br_RFnSwR92um", + "@timestamp": "21:28:13.953" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcYZt50Br_RFnSwRmW_c", + "@timestamp": "21:30:01.382" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yat50Br_RFnSwRA3BZ", + "@timestamp": "21:30:28.410" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ScYat50Br_RFnSwRHnG2", + "@timestamp": "21:30:35.254" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ksYat50Br_RFnSwRwnPN", + "@timestamp": "21:31:17.237" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ocYbt50Br_RFnSwRW3Us", + "@timestamp": "21:31:55.636" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "isYct50Br_RFnSwRCnj5", + "@timestamp": "21:32:40.871" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yct50Br_RFnSwRGniZ", + "@timestamp": "21:32:45.287" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "ef1830bae2b06545f2a0ce5082b28603", + "@timestamp": "21:22:56", + "user_action": "user_checkout_multi" + }, + { + "traceID": "9ba2397f2ded4d7ece094390cdab35e5", + "@timestamp": "21:23:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "2f408f49c74e7eea3612ef826f10f421", + "@timestamp": "21:23:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "096d4942de145bb342e6959b152b52e0", + "@timestamp": "21:24:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a8a4d188026cbf1bf78b0dabde9662e2", + "@timestamp": "21:25:21", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f14a727ca1de784762fdc8d49a788989", + "@timestamp": "21:25:22", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7f40ec3e191d9be6b09396b5194f21de", + "@timestamp": "21:25:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6e725c6b333de8026b05a16bf7f4a619", + "@timestamp": "21:26:19", + "user_action": "user_checkout_single" + }, + { + "traceID": "8f64663d763e5607f2943043aadcd53d", + "@timestamp": "21:26:53", + "user_action": "user_checkout_single" + }, + { + "traceID": "d6fe178e3ac626e359d37e4a18bf4f71", + "@timestamp": "21:26:55", + "user_action": "user_checkout_single" + }, + { + "traceID": "0a0f9239ebb6afdd0015c315c816b4a1", + "@timestamp": "21:26:59", + "user_action": "user_checkout_single" + }, + { + "traceID": "4e3bb300c7f158ff428414804727359e", + "@timestamp": "21:27:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cca1ebb62eca649ce47b9c0d64b186d1", + "@timestamp": "21:27:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "accdadceaf5af68cf0be327155f9f2ac", + "@timestamp": "21:28:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "6a7beb8972f9e43fffb874210034c9d3", + "@timestamp": "21:30:01", + "user_action": "user_checkout_single" + }, + { + "traceID": "9039f2ae7a68223da4113f72eb81dc83", + "@timestamp": "21:30:28", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5dcb2636f02200ebe76974ae944c1965", + "@timestamp": "21:30:35", + "user_action": "user_checkout_single" + }, + { + "traceID": "5ef605bd79cfb4907d80db49d4e57701", + "@timestamp": "21:31:17", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e05f457e54ebfb886701005b1c90734a", + "@timestamp": "21:31:55", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b0f522f893442746d64bfab844df9c7", + "@timestamp": "21:32:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fee034208640c0d39ee49e002446fa52", + "@timestamp": "21:32:45", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/solve.py b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/solve.sh b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/check_prediction.py b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/expected.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..fa1dceaf523a0db567fec1978e685552ba6e4cff --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d4-d3dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-22T20:52:46.740910+00:00" + }, + { + "event_id": "d4-d3dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-22T18:52:17.653473+00:00" + }, + { + "event_id": "d4-d3dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-22T20:22:41.236522+00:00" + }, + { + "event_id": "d4-d3dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-22T21:22:52.483960+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..e55cb50e5ea8db42bed372710d0f6b475b1f759c --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json @@ -0,0 +1,200 @@ +{ + "incident_time": "2026-04-22T20:22:41.236522+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the payment service's Charge RPC. Was zero before the incident; the paymentFailure flag causes ~10% of charge calls to throw, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram count for payment Charge errors. Was zero before the incident; each failed charge produces a duration sample in this histogram.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:28. The first non-zero value appears at 20:29 (0.00416667), which is about 6 minutes after the incident time. This is the clear onset of the spike above the zero baseline." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration sum for payment Charge errors. Was zero before the incident; tracks cumulative latency of failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00426, which is the first non-zero value after the incident time (20:22:41). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram buckets for payment Charge errors. Was zero before the incident; populates latency distribution buckets for failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The baseline is 0 throughout the pre-incident period. After the incident at 20:22:41 UTC, the metric remains at 0 until 20:29:00 UTC when it first spikes to 0.0708333, clearly rising above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": "2026-04-22 20:24:00 UTC", + "onset_offset_seconds": 78, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:23. At 20:24 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"checkout\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the checkout service's client-side PaymentService/Charge span. Was zero before the incident; errors from the payment service propagate as gRPC errors on the checkout side.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:27:53 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "IsXgtp0Br_RFnSwRubU5", + "@timestamp": "20:27:53.167" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:27:53 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "ksXgtp0Br_RFnSwRy7W0", + "@timestamp": "20:27:53.198" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:27:53 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2de5b0fee49445b07e09b4338ca9f884", + "@timestamp": "20:27:53", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7db86e578213a88b97fea945d9a0c0a8ac87bb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json @@ -0,0 +1,301 @@ +{ + "incident_time": "2026-04-22T20:52:46.740910+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call rate for payment service's Charge RPC with error status. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, producing new STATUS_CODE_ERROR spans on the payment service.", + "onset_utc": "2026-04-22 20:55:00 UTC", + "onset_offset_seconds": 133, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors (~0.004 or 0) with many zero values. After the incident at 20:52:46, the metric jumps to 0.00833333 at 20:55:00 — roughly 2x the previous sporadic baseline — and sustains elevated values (0.008–0.02) from that point onward, indicating the clear start of the error spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_service": "oteldemo.PaymentService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_service=\"oteldemo.PaymentService\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC client calls to PaymentService/Charge returning Unknown (code 2) status spiked as the payment service throws errors when the paymentFailure flag triggers", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline oscillates between 0 and ~0.00417. After the incident at 20:52:46, the value at 20:54 jumps to 0.00833, which is 2x the baseline, and continues rising to a peak of ~0.0208 at 21:00. This is the first timestamp after the incident where the metric clearly exceeds the pre-incident range." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout requests returning HTTP 500 increased as the paymentFailure flag causes ~50% of payment charges to throw errors, which propagate through checkout as gRPC Internal errors and surface as HTTP 500 responses", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (~0.004) interspersed with zeros. After the incident at 20:52:46, the first post-incident nonzero value at 20:54 is 0.00833, which is ~2x the baseline sporadic value, and it sustains and climbs further (0.0125, 0.0167, 0.0208), confirming a clear spike onset at 20:54." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag with variant '50%' stepped from 2 to 3 at incident time, recording the flag configuration change that activated the 50% payment failure rate", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "The metric holds steady at 2 from 20:32 through 20:53. At 20:54 it jumps to 3 and remains there, which is the first timestamp after the incident time (20:52:46) showing a clear rise above the baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_service": "oteldemo.CheckoutService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.CheckoutService\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout gRPC server calls returning Internal (code 13) status increased as payment failures propagate through checkout's PlaceOrder handler which returns codes.Internal when chargeCard fails", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (0 to ~0.00417). After the incident at 20:52:46, the metric jumps to 0.00833 at 20:54 — double the previous max baseline value — and continues rising to a peak of ~0.0208 at 21:00, confirming a clear spike. 20:54 is the first post-incident timestamp with a sustained elevated value." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "Ccb3tp0Br_RFnSwRwgM9", + "@timestamp": "20:53:03.061" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "A8b3tp0Br_RFnSwR4QTz", + "@timestamp": "20:53:11.157" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OMb6tp0Br_RFnSwRkQw4", + "@timestamp": "20:56:07.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcb6tp0Br_RFnSwR6w2J", + "@timestamp": "20:56:30.579" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "jcb7tp0Br_RFnSwRHg5O", + "@timestamp": "20:56:43.267" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "zMb8tp0Br_RFnSwRJxHB", + "@timestamp": "20:57:51.593" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "tcb8tp0Br_RFnSwRyxPZ", + "@timestamp": "20:58:33.292" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "TMb_tp0Br_RFnSwRLRpT", + "@timestamp": "21:01:09.017" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "osYAt50Br_RFnSwREBxE", + "@timestamp": "21:02:07.788" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–43ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tsb3tp0Br_RFnSwR1gNn", + "@timestamp": "20:53:03.104" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "iMb3tp0Br_RFnSwR9QTa", + "@timestamp": "20:53:11.181" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "08b6tp0Br_RFnSwRpQza", + "@timestamp": "20:56:07.671" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Pcb6tp0Br_RFnSwR_w7i", + "@timestamp": "20:56:30.622" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "CMb7tp0Br_RFnSwRMg_c", + "@timestamp": "20:56:43.293" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "UMb8tp0Br_RFnSwRPBLk", + "@timestamp": "20:57:51.613" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Gcb8tp0Br_RFnSwR4RQw", + "@timestamp": "20:58:33.317" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "icb_tp0Br_RFnSwRPhry", + "@timestamp": "21:01:09.047" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "VsYAt50Br_RFnSwRJR2k", + "@timestamp": "21:02:07.828" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:53:02 and 21:02:07 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "66b9ba801adf9f9f422434a778f79537", + "@timestamp": "20:53:02", + "user_action": "user_checkout_multi" + }, + { + "traceID": "72837353452f8a345bec058d3d020268", + "@timestamp": "20:53:11", + "user_action": "user_checkout_single" + }, + { + "traceID": "f255f946901777cd31f6d12a5f098a9e", + "@timestamp": "20:56:07", + "user_action": "user_checkout_single" + }, + { + "traceID": "f45d35ba65bccb4c4978380da5646dbc", + "@timestamp": "20:56:30", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b206613c795a05a3544ea6896b7691b", + "@timestamp": "20:56:43", + "user_action": "user_checkout_single" + }, + { + "traceID": "ad89464077ece735dd371b3d222a868d", + "@timestamp": "20:57:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "f394303704028931b06bfd39a4597301", + "@timestamp": "20:58:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "e021d85134fb82acc1f87a9e52abaf43", + "@timestamp": "21:01:08", + "user_action": "user_checkout_single" + }, + { + "traceID": "804e3624540aa57a66685981d6aa655a", + "@timestamp": "21:02:07", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cffa8510af04230dcb573fbf0b4f7aa4adf8d972 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json @@ -0,0 +1,357 @@ +{ + "incident_time": "2026-04-22T21:22:52.483960+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "0", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"0\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "Successful (OK) gRPC Charge calls from checkout to payment dropped to zero because the gRPC client is directed at badAddress:50051 which fails DNS resolution", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "Pre-incident, the metric oscillates between ~0.004 and ~0.017 with typical values around 0.008. After the incident at 21:22:52, the value at 21:23 is 0.00417 (still within normal range), then 21:24 shows 0.00417 as the last non-zero reading. From 21:25 onward the signal drops to zero and never recovers. The onset is 21:24 — the last timestamp showing pre-incident activity before the collapse." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "14", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"14\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "New gRPC UNAVAILABLE (code 14) errors appeared on checkout's client calls to PaymentService/Charge — the gRPC dial to badAddress:50051 fails with DNS resolution error", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric is flat at 0 from 21:02 through 21:23 (including the incident marker). At 21:24 it jumps to 0.00417, the first non-zero value, and continues rising steadily thereafter. This is the clear onset of the spike." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "propagation", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate", + "description": "Kafka consumer byte consumption rate dropped to zero because no order records are being produced to the orders topic, leaving the fraud-detection consumer with nothing to consume", + "onset_utc": "2026-04-22 21:21:00 UTC", + "onset_offset_seconds": -112, + "onset_reasoning": "Pre-incident pattern shows periodic non-zero values every 1-3 minutes (9.25, 9.54, 5.48, 8.7, 4.08, 4.35, 4.51, 4.27, 4.95). The last non-zero value is at 21:21 (4.9464). From 21:22 onward the signal is permanently zero, aligning with the incident at 21:22:52. This is the last active timestamp before the collapse." + } + ] + }, + { + "metric_family": "app_confirmation_counter", + "signal_layer": "symptom", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_confirmation_counter_total[5m])", + "description": "Checkout order confirmation rate dropped to zero because every checkout fails at the payment step, so no order confirmation emails are sent", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low but non-zero activity (oscillating around 0.004-0.017) before the incident. At 21:24 the value is 0.00416642, and from 21:25 onward it drops to zero permanently. The last non-trivial value is at 21:24, marking the final moment the pre-incident pattern is still active before the signal collapses." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "type": "log" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\", type=\"log\"}[5m])", + "description": "OTLP exporter record counter for logs exported by the fraud-detection service. Collapsed to zero because fraud-detection produces no order-processing logs when no orders arrive via Kafka.", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low-level periodic activity (oscillating roughly 0.004–0.017) before the incident. At 21:24 the value is 0.00416667, and from 21:25 onward it drops to 0 permanently. So 21:24 is the last timestamp with non-zero activity before the signal collapses, aligning closely with the incident time of 21:22:52." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-22T21:22:56.660Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 372 21 37 36 \"-\" \"python-requests/2.32.5\" \"39765a6c-ead4-9254-b089-6d267091fe68\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:60672 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "zMYTt50Br_RFnSwRIFmm", + "@timestamp": "21:22:56.660" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "q8YTt50Br_RFnSwRuVsu", + "@timestamp": "21:23:36.192" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OsYTt50Br_RFnSwR2Fxc", + "@timestamp": "21:23:43.528" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYUt50Br_RFnSwRt18x", + "@timestamp": "21:24:40.599" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "JMYVt50Br_RFnSwRU2G7", + "@timestamp": "21:25:21.132" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "b8YVt50Br_RFnSwRW2GB", + "@timestamp": "21:25:23.001" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cYVt50Br_RFnSwR6GM2", + "@timestamp": "21:25:59.000" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "bMYWt50Br_RFnSwROmVG", + "@timestamp": "21:26:19.473" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "58YWt50Br_RFnSwRv2Yb", + "@timestamp": "21:26:53.885" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYWt50Br_RFnSwRxmfp", + "@timestamp": "21:26:55.839" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "mMYWt50Br_RFnSwR1meH", + "@timestamp": "21:26:59.477" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "NMYXt50Br_RFnSwRfmmP", + "@timestamp": "21:27:43.350" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "FMYXt50Br_RFnSwRoWqt", + "@timestamp": "21:27:51.861" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "f8YXt50Br_RFnSwR92um", + "@timestamp": "21:28:13.953" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcYZt50Br_RFnSwRmW_c", + "@timestamp": "21:30:01.382" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yat50Br_RFnSwRA3BZ", + "@timestamp": "21:30:28.410" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ScYat50Br_RFnSwRHnG2", + "@timestamp": "21:30:35.254" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ksYat50Br_RFnSwRwnPN", + "@timestamp": "21:31:17.237" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ocYbt50Br_RFnSwRW3Us", + "@timestamp": "21:31:55.636" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "isYct50Br_RFnSwRCnj5", + "@timestamp": "21:32:40.871" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yct50Br_RFnSwRGniZ", + "@timestamp": "21:32:45.287" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "ef1830bae2b06545f2a0ce5082b28603", + "@timestamp": "21:22:56", + "user_action": "user_checkout_multi" + }, + { + "traceID": "9ba2397f2ded4d7ece094390cdab35e5", + "@timestamp": "21:23:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "2f408f49c74e7eea3612ef826f10f421", + "@timestamp": "21:23:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "096d4942de145bb342e6959b152b52e0", + "@timestamp": "21:24:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a8a4d188026cbf1bf78b0dabde9662e2", + "@timestamp": "21:25:21", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f14a727ca1de784762fdc8d49a788989", + "@timestamp": "21:25:22", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7f40ec3e191d9be6b09396b5194f21de", + "@timestamp": "21:25:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6e725c6b333de8026b05a16bf7f4a619", + "@timestamp": "21:26:19", + "user_action": "user_checkout_single" + }, + { + "traceID": "8f64663d763e5607f2943043aadcd53d", + "@timestamp": "21:26:53", + "user_action": "user_checkout_single" + }, + { + "traceID": "d6fe178e3ac626e359d37e4a18bf4f71", + "@timestamp": "21:26:55", + "user_action": "user_checkout_single" + }, + { + "traceID": "0a0f9239ebb6afdd0015c315c816b4a1", + "@timestamp": "21:26:59", + "user_action": "user_checkout_single" + }, + { + "traceID": "4e3bb300c7f158ff428414804727359e", + "@timestamp": "21:27:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cca1ebb62eca649ce47b9c0d64b186d1", + "@timestamp": "21:27:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "accdadceaf5af68cf0be327155f9f2ac", + "@timestamp": "21:28:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "6a7beb8972f9e43fffb874210034c9d3", + "@timestamp": "21:30:01", + "user_action": "user_checkout_single" + }, + { + "traceID": "9039f2ae7a68223da4113f72eb81dc83", + "@timestamp": "21:30:28", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5dcb2636f02200ebe76974ae944c1965", + "@timestamp": "21:30:35", + "user_action": "user_checkout_single" + }, + { + "traceID": "5ef605bd79cfb4907d80db49d4e57701", + "@timestamp": "21:31:17", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e05f457e54ebfb886701005b1c90734a", + "@timestamp": "21:31:55", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b0f522f893442746d64bfab844df9c7", + "@timestamp": "21:32:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fee034208640c0d39ee49e002446fa52", + "@timestamp": "21:32:45", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/test.sh b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-02-hard_ttd480m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/environment/Dockerfile b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/environment/docker-compose.yaml b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/check_prediction.py b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubric.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7db86e578213a88b97fea945d9a0c0a8ac87bb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubric.json @@ -0,0 +1,301 @@ +{ + "incident_time": "2026-04-22T20:52:46.740910+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call rate for payment service's Charge RPC with error status. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, producing new STATUS_CODE_ERROR spans on the payment service.", + "onset_utc": "2026-04-22 20:55:00 UTC", + "onset_offset_seconds": 133, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors (~0.004 or 0) with many zero values. After the incident at 20:52:46, the metric jumps to 0.00833333 at 20:55:00 — roughly 2x the previous sporadic baseline — and sustains elevated values (0.008–0.02) from that point onward, indicating the clear start of the error spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_service": "oteldemo.PaymentService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_service=\"oteldemo.PaymentService\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC client calls to PaymentService/Charge returning Unknown (code 2) status spiked as the payment service throws errors when the paymentFailure flag triggers", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline oscillates between 0 and ~0.00417. After the incident at 20:52:46, the value at 20:54 jumps to 0.00833, which is 2x the baseline, and continues rising to a peak of ~0.0208 at 21:00. This is the first timestamp after the incident where the metric clearly exceeds the pre-incident range." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout requests returning HTTP 500 increased as the paymentFailure flag causes ~50% of payment charges to throw errors, which propagate through checkout as gRPC Internal errors and surface as HTTP 500 responses", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (~0.004) interspersed with zeros. After the incident at 20:52:46, the first post-incident nonzero value at 20:54 is 0.00833, which is ~2x the baseline sporadic value, and it sustains and climbs further (0.0125, 0.0167, 0.0208), confirming a clear spike onset at 20:54." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag with variant '50%' stepped from 2 to 3 at incident time, recording the flag configuration change that activated the 50% payment failure rate", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "The metric holds steady at 2 from 20:32 through 20:53. At 20:54 it jumps to 3 and remains there, which is the first timestamp after the incident time (20:52:46) showing a clear rise above the baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_service": "oteldemo.CheckoutService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.CheckoutService\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout gRPC server calls returning Internal (code 13) status increased as payment failures propagate through checkout's PlaceOrder handler which returns codes.Internal when chargeCard fails", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (0 to ~0.00417). After the incident at 20:52:46, the metric jumps to 0.00833 at 20:54 — double the previous max baseline value — and continues rising to a peak of ~0.0208 at 21:00, confirming a clear spike. 20:54 is the first post-incident timestamp with a sustained elevated value." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "Ccb3tp0Br_RFnSwRwgM9", + "@timestamp": "20:53:03.061" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "A8b3tp0Br_RFnSwR4QTz", + "@timestamp": "20:53:11.157" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OMb6tp0Br_RFnSwRkQw4", + "@timestamp": "20:56:07.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcb6tp0Br_RFnSwR6w2J", + "@timestamp": "20:56:30.579" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "jcb7tp0Br_RFnSwRHg5O", + "@timestamp": "20:56:43.267" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "zMb8tp0Br_RFnSwRJxHB", + "@timestamp": "20:57:51.593" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "tcb8tp0Br_RFnSwRyxPZ", + "@timestamp": "20:58:33.292" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "TMb_tp0Br_RFnSwRLRpT", + "@timestamp": "21:01:09.017" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "osYAt50Br_RFnSwREBxE", + "@timestamp": "21:02:07.788" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–43ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tsb3tp0Br_RFnSwR1gNn", + "@timestamp": "20:53:03.104" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "iMb3tp0Br_RFnSwR9QTa", + "@timestamp": "20:53:11.181" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "08b6tp0Br_RFnSwRpQza", + "@timestamp": "20:56:07.671" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Pcb6tp0Br_RFnSwR_w7i", + "@timestamp": "20:56:30.622" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "CMb7tp0Br_RFnSwRMg_c", + "@timestamp": "20:56:43.293" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "UMb8tp0Br_RFnSwRPBLk", + "@timestamp": "20:57:51.613" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Gcb8tp0Br_RFnSwR4RQw", + "@timestamp": "20:58:33.317" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "icb_tp0Br_RFnSwRPhry", + "@timestamp": "21:01:09.047" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "VsYAt50Br_RFnSwRJR2k", + "@timestamp": "21:02:07.828" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:53:02 and 21:02:07 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "66b9ba801adf9f9f422434a778f79537", + "@timestamp": "20:53:02", + "user_action": "user_checkout_multi" + }, + { + "traceID": "72837353452f8a345bec058d3d020268", + "@timestamp": "20:53:11", + "user_action": "user_checkout_single" + }, + { + "traceID": "f255f946901777cd31f6d12a5f098a9e", + "@timestamp": "20:56:07", + "user_action": "user_checkout_single" + }, + { + "traceID": "f45d35ba65bccb4c4978380da5646dbc", + "@timestamp": "20:56:30", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b206613c795a05a3544ea6896b7691b", + "@timestamp": "20:56:43", + "user_action": "user_checkout_single" + }, + { + "traceID": "ad89464077ece735dd371b3d222a868d", + "@timestamp": "20:57:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "f394303704028931b06bfd39a4597301", + "@timestamp": "20:58:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "e021d85134fb82acc1f87a9e52abaf43", + "@timestamp": "21:01:08", + "user_action": "user_checkout_single" + }, + { + "traceID": "804e3624540aa57a66685981d6aa655a", + "@timestamp": "21:02:07", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..e55cb50e5ea8db42bed372710d0f6b475b1f759c --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json @@ -0,0 +1,200 @@ +{ + "incident_time": "2026-04-22T20:22:41.236522+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the payment service's Charge RPC. Was zero before the incident; the paymentFailure flag causes ~10% of charge calls to throw, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram count for payment Charge errors. Was zero before the incident; each failed charge produces a duration sample in this histogram.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:28. The first non-zero value appears at 20:29 (0.00416667), which is about 6 minutes after the incident time. This is the clear onset of the spike above the zero baseline." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration sum for payment Charge errors. Was zero before the incident; tracks cumulative latency of failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00426, which is the first non-zero value after the incident time (20:22:41). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram buckets for payment Charge errors. Was zero before the incident; populates latency distribution buckets for failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The baseline is 0 throughout the pre-incident period. After the incident at 20:22:41 UTC, the metric remains at 0 until 20:29:00 UTC when it first spikes to 0.0708333, clearly rising above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": "2026-04-22 20:24:00 UTC", + "onset_offset_seconds": 78, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:23. At 20:24 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"checkout\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the checkout service's client-side PaymentService/Charge span. Was zero before the incident; errors from the payment service propagate as gRPC errors on the checkout side.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:27:53 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "IsXgtp0Br_RFnSwRubU5", + "@timestamp": "20:27:53.167" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:27:53 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "ksXgtp0Br_RFnSwRy7W0", + "@timestamp": "20:27:53.198" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:27:53 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2de5b0fee49445b07e09b4338ca9f884", + "@timestamp": "20:27:53", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7db86e578213a88b97fea945d9a0c0a8ac87bb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json @@ -0,0 +1,301 @@ +{ + "incident_time": "2026-04-22T20:52:46.740910+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call rate for payment service's Charge RPC with error status. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, producing new STATUS_CODE_ERROR spans on the payment service.", + "onset_utc": "2026-04-22 20:55:00 UTC", + "onset_offset_seconds": 133, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors (~0.004 or 0) with many zero values. After the incident at 20:52:46, the metric jumps to 0.00833333 at 20:55:00 — roughly 2x the previous sporadic baseline — and sustains elevated values (0.008–0.02) from that point onward, indicating the clear start of the error spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_service": "oteldemo.PaymentService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_service=\"oteldemo.PaymentService\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC client calls to PaymentService/Charge returning Unknown (code 2) status spiked as the payment service throws errors when the paymentFailure flag triggers", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline oscillates between 0 and ~0.00417. After the incident at 20:52:46, the value at 20:54 jumps to 0.00833, which is 2x the baseline, and continues rising to a peak of ~0.0208 at 21:00. This is the first timestamp after the incident where the metric clearly exceeds the pre-incident range." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout requests returning HTTP 500 increased as the paymentFailure flag causes ~50% of payment charges to throw errors, which propagate through checkout as gRPC Internal errors and surface as HTTP 500 responses", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (~0.004) interspersed with zeros. After the incident at 20:52:46, the first post-incident nonzero value at 20:54 is 0.00833, which is ~2x the baseline sporadic value, and it sustains and climbs further (0.0125, 0.0167, 0.0208), confirming a clear spike onset at 20:54." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag with variant '50%' stepped from 2 to 3 at incident time, recording the flag configuration change that activated the 50% payment failure rate", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "The metric holds steady at 2 from 20:32 through 20:53. At 20:54 it jumps to 3 and remains there, which is the first timestamp after the incident time (20:52:46) showing a clear rise above the baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_service": "oteldemo.CheckoutService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.CheckoutService\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout gRPC server calls returning Internal (code 13) status increased as payment failures propagate through checkout's PlaceOrder handler which returns codes.Internal when chargeCard fails", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (0 to ~0.00417). After the incident at 20:52:46, the metric jumps to 0.00833 at 20:54 — double the previous max baseline value — and continues rising to a peak of ~0.0208 at 21:00, confirming a clear spike. 20:54 is the first post-incident timestamp with a sustained elevated value." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "Ccb3tp0Br_RFnSwRwgM9", + "@timestamp": "20:53:03.061" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "A8b3tp0Br_RFnSwR4QTz", + "@timestamp": "20:53:11.157" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OMb6tp0Br_RFnSwRkQw4", + "@timestamp": "20:56:07.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcb6tp0Br_RFnSwR6w2J", + "@timestamp": "20:56:30.579" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "jcb7tp0Br_RFnSwRHg5O", + "@timestamp": "20:56:43.267" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "zMb8tp0Br_RFnSwRJxHB", + "@timestamp": "20:57:51.593" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "tcb8tp0Br_RFnSwRyxPZ", + "@timestamp": "20:58:33.292" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "TMb_tp0Br_RFnSwRLRpT", + "@timestamp": "21:01:09.017" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "osYAt50Br_RFnSwREBxE", + "@timestamp": "21:02:07.788" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–43ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tsb3tp0Br_RFnSwR1gNn", + "@timestamp": "20:53:03.104" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "iMb3tp0Br_RFnSwR9QTa", + "@timestamp": "20:53:11.181" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "08b6tp0Br_RFnSwRpQza", + "@timestamp": "20:56:07.671" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Pcb6tp0Br_RFnSwR_w7i", + "@timestamp": "20:56:30.622" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "CMb7tp0Br_RFnSwRMg_c", + "@timestamp": "20:56:43.293" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "UMb8tp0Br_RFnSwRPBLk", + "@timestamp": "20:57:51.613" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Gcb8tp0Br_RFnSwR4RQw", + "@timestamp": "20:58:33.317" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "icb_tp0Br_RFnSwRPhry", + "@timestamp": "21:01:09.047" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "VsYAt50Br_RFnSwRJR2k", + "@timestamp": "21:02:07.828" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:53:02 and 21:02:07 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "66b9ba801adf9f9f422434a778f79537", + "@timestamp": "20:53:02", + "user_action": "user_checkout_multi" + }, + { + "traceID": "72837353452f8a345bec058d3d020268", + "@timestamp": "20:53:11", + "user_action": "user_checkout_single" + }, + { + "traceID": "f255f946901777cd31f6d12a5f098a9e", + "@timestamp": "20:56:07", + "user_action": "user_checkout_single" + }, + { + "traceID": "f45d35ba65bccb4c4978380da5646dbc", + "@timestamp": "20:56:30", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b206613c795a05a3544ea6896b7691b", + "@timestamp": "20:56:43", + "user_action": "user_checkout_single" + }, + { + "traceID": "ad89464077ece735dd371b3d222a868d", + "@timestamp": "20:57:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "f394303704028931b06bfd39a4597301", + "@timestamp": "20:58:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "e021d85134fb82acc1f87a9e52abaf43", + "@timestamp": "21:01:08", + "user_action": "user_checkout_single" + }, + { + "traceID": "804e3624540aa57a66685981d6aa655a", + "@timestamp": "21:02:07", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cffa8510af04230dcb573fbf0b4f7aa4adf8d972 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json @@ -0,0 +1,357 @@ +{ + "incident_time": "2026-04-22T21:22:52.483960+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "0", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"0\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "Successful (OK) gRPC Charge calls from checkout to payment dropped to zero because the gRPC client is directed at badAddress:50051 which fails DNS resolution", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "Pre-incident, the metric oscillates between ~0.004 and ~0.017 with typical values around 0.008. After the incident at 21:22:52, the value at 21:23 is 0.00417 (still within normal range), then 21:24 shows 0.00417 as the last non-zero reading. From 21:25 onward the signal drops to zero and never recovers. The onset is 21:24 — the last timestamp showing pre-incident activity before the collapse." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "14", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"14\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "New gRPC UNAVAILABLE (code 14) errors appeared on checkout's client calls to PaymentService/Charge — the gRPC dial to badAddress:50051 fails with DNS resolution error", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric is flat at 0 from 21:02 through 21:23 (including the incident marker). At 21:24 it jumps to 0.00417, the first non-zero value, and continues rising steadily thereafter. This is the clear onset of the spike." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "propagation", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate", + "description": "Kafka consumer byte consumption rate dropped to zero because no order records are being produced to the orders topic, leaving the fraud-detection consumer with nothing to consume", + "onset_utc": "2026-04-22 21:21:00 UTC", + "onset_offset_seconds": -112, + "onset_reasoning": "Pre-incident pattern shows periodic non-zero values every 1-3 minutes (9.25, 9.54, 5.48, 8.7, 4.08, 4.35, 4.51, 4.27, 4.95). The last non-zero value is at 21:21 (4.9464). From 21:22 onward the signal is permanently zero, aligning with the incident at 21:22:52. This is the last active timestamp before the collapse." + } + ] + }, + { + "metric_family": "app_confirmation_counter", + "signal_layer": "symptom", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_confirmation_counter_total[5m])", + "description": "Checkout order confirmation rate dropped to zero because every checkout fails at the payment step, so no order confirmation emails are sent", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low but non-zero activity (oscillating around 0.004-0.017) before the incident. At 21:24 the value is 0.00416642, and from 21:25 onward it drops to zero permanently. The last non-trivial value is at 21:24, marking the final moment the pre-incident pattern is still active before the signal collapses." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "type": "log" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\", type=\"log\"}[5m])", + "description": "OTLP exporter record counter for logs exported by the fraud-detection service. Collapsed to zero because fraud-detection produces no order-processing logs when no orders arrive via Kafka.", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low-level periodic activity (oscillating roughly 0.004–0.017) before the incident. At 21:24 the value is 0.00416667, and from 21:25 onward it drops to 0 permanently. So 21:24 is the last timestamp with non-zero activity before the signal collapses, aligning closely with the incident time of 21:22:52." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-22T21:22:56.660Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 372 21 37 36 \"-\" \"python-requests/2.32.5\" \"39765a6c-ead4-9254-b089-6d267091fe68\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:60672 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "zMYTt50Br_RFnSwRIFmm", + "@timestamp": "21:22:56.660" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "q8YTt50Br_RFnSwRuVsu", + "@timestamp": "21:23:36.192" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OsYTt50Br_RFnSwR2Fxc", + "@timestamp": "21:23:43.528" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYUt50Br_RFnSwRt18x", + "@timestamp": "21:24:40.599" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "JMYVt50Br_RFnSwRU2G7", + "@timestamp": "21:25:21.132" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "b8YVt50Br_RFnSwRW2GB", + "@timestamp": "21:25:23.001" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cYVt50Br_RFnSwR6GM2", + "@timestamp": "21:25:59.000" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "bMYWt50Br_RFnSwROmVG", + "@timestamp": "21:26:19.473" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "58YWt50Br_RFnSwRv2Yb", + "@timestamp": "21:26:53.885" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYWt50Br_RFnSwRxmfp", + "@timestamp": "21:26:55.839" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "mMYWt50Br_RFnSwR1meH", + "@timestamp": "21:26:59.477" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "NMYXt50Br_RFnSwRfmmP", + "@timestamp": "21:27:43.350" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "FMYXt50Br_RFnSwRoWqt", + "@timestamp": "21:27:51.861" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "f8YXt50Br_RFnSwR92um", + "@timestamp": "21:28:13.953" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcYZt50Br_RFnSwRmW_c", + "@timestamp": "21:30:01.382" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yat50Br_RFnSwRA3BZ", + "@timestamp": "21:30:28.410" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ScYat50Br_RFnSwRHnG2", + "@timestamp": "21:30:35.254" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ksYat50Br_RFnSwRwnPN", + "@timestamp": "21:31:17.237" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ocYbt50Br_RFnSwRW3Us", + "@timestamp": "21:31:55.636" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "isYct50Br_RFnSwRCnj5", + "@timestamp": "21:32:40.871" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yct50Br_RFnSwRGniZ", + "@timestamp": "21:32:45.287" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "ef1830bae2b06545f2a0ce5082b28603", + "@timestamp": "21:22:56", + "user_action": "user_checkout_multi" + }, + { + "traceID": "9ba2397f2ded4d7ece094390cdab35e5", + "@timestamp": "21:23:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "2f408f49c74e7eea3612ef826f10f421", + "@timestamp": "21:23:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "096d4942de145bb342e6959b152b52e0", + "@timestamp": "21:24:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a8a4d188026cbf1bf78b0dabde9662e2", + "@timestamp": "21:25:21", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f14a727ca1de784762fdc8d49a788989", + "@timestamp": "21:25:22", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7f40ec3e191d9be6b09396b5194f21de", + "@timestamp": "21:25:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6e725c6b333de8026b05a16bf7f4a619", + "@timestamp": "21:26:19", + "user_action": "user_checkout_single" + }, + { + "traceID": "8f64663d763e5607f2943043aadcd53d", + "@timestamp": "21:26:53", + "user_action": "user_checkout_single" + }, + { + "traceID": "d6fe178e3ac626e359d37e4a18bf4f71", + "@timestamp": "21:26:55", + "user_action": "user_checkout_single" + }, + { + "traceID": "0a0f9239ebb6afdd0015c315c816b4a1", + "@timestamp": "21:26:59", + "user_action": "user_checkout_single" + }, + { + "traceID": "4e3bb300c7f158ff428414804727359e", + "@timestamp": "21:27:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cca1ebb62eca649ce47b9c0d64b186d1", + "@timestamp": "21:27:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "accdadceaf5af68cf0be327155f9f2ac", + "@timestamp": "21:28:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "6a7beb8972f9e43fffb874210034c9d3", + "@timestamp": "21:30:01", + "user_action": "user_checkout_single" + }, + { + "traceID": "9039f2ae7a68223da4113f72eb81dc83", + "@timestamp": "21:30:28", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5dcb2636f02200ebe76974ae944c1965", + "@timestamp": "21:30:35", + "user_action": "user_checkout_single" + }, + { + "traceID": "5ef605bd79cfb4907d80db49d4e57701", + "@timestamp": "21:31:17", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e05f457e54ebfb886701005b1c90734a", + "@timestamp": "21:31:55", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b0f522f893442746d64bfab844df9c7", + "@timestamp": "21:32:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fee034208640c0d39ee49e002446fa52", + "@timestamp": "21:32:45", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/solve.py b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/solve.sh b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/check_prediction.py b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/expected.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..fa1dceaf523a0db567fec1978e685552ba6e4cff --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d4-d3dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-22T20:52:46.740910+00:00" + }, + { + "event_id": "d4-d3dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-22T18:52:17.653473+00:00" + }, + { + "event_id": "d4-d3dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-22T20:22:41.236522+00:00" + }, + { + "event_id": "d4-d3dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-22T21:22:52.483960+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..e55cb50e5ea8db42bed372710d0f6b475b1f759c --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json @@ -0,0 +1,200 @@ +{ + "incident_time": "2026-04-22T20:22:41.236522+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the payment service's Charge RPC. Was zero before the incident; the paymentFailure flag causes ~10% of charge calls to throw, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram count for payment Charge errors. Was zero before the incident; each failed charge produces a duration sample in this histogram.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:28. The first non-zero value appears at 20:29 (0.00416667), which is about 6 minutes after the incident time. This is the clear onset of the spike above the zero baseline." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration sum for payment Charge errors. Was zero before the incident; tracks cumulative latency of failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00426, which is the first non-zero value after the incident time (20:22:41). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram buckets for payment Charge errors. Was zero before the incident; populates latency distribution buckets for failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The baseline is 0 throughout the pre-incident period. After the incident at 20:22:41 UTC, the metric remains at 0 until 20:29:00 UTC when it first spikes to 0.0708333, clearly rising above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": "2026-04-22 20:24:00 UTC", + "onset_offset_seconds": 78, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:23. At 20:24 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"checkout\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the checkout service's client-side PaymentService/Charge span. Was zero before the incident; errors from the payment service propagate as gRPC errors on the checkout side.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:27:53 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "IsXgtp0Br_RFnSwRubU5", + "@timestamp": "20:27:53.167" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:27:53 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "ksXgtp0Br_RFnSwRy7W0", + "@timestamp": "20:27:53.198" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:27:53 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2de5b0fee49445b07e09b4338ca9f884", + "@timestamp": "20:27:53", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7db86e578213a88b97fea945d9a0c0a8ac87bb --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json @@ -0,0 +1,301 @@ +{ + "incident_time": "2026-04-22T20:52:46.740910+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call rate for payment service's Charge RPC with error status. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, producing new STATUS_CODE_ERROR spans on the payment service.", + "onset_utc": "2026-04-22 20:55:00 UTC", + "onset_offset_seconds": 133, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors (~0.004 or 0) with many zero values. After the incident at 20:52:46, the metric jumps to 0.00833333 at 20:55:00 — roughly 2x the previous sporadic baseline — and sustains elevated values (0.008–0.02) from that point onward, indicating the clear start of the error spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_service": "oteldemo.PaymentService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_service=\"oteldemo.PaymentService\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC client calls to PaymentService/Charge returning Unknown (code 2) status spiked as the payment service throws errors when the paymentFailure flag triggers", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline oscillates between 0 and ~0.00417. After the incident at 20:52:46, the value at 20:54 jumps to 0.00833, which is 2x the baseline, and continues rising to a peak of ~0.0208 at 21:00. This is the first timestamp after the incident where the metric clearly exceeds the pre-incident range." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout requests returning HTTP 500 increased as the paymentFailure flag causes ~50% of payment charges to throw errors, which propagate through checkout as gRPC Internal errors and surface as HTTP 500 responses", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (~0.004) interspersed with zeros. After the incident at 20:52:46, the first post-incident nonzero value at 20:54 is 0.00833, which is ~2x the baseline sporadic value, and it sustains and climbs further (0.0125, 0.0167, 0.0208), confirming a clear spike onset at 20:54." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag with variant '50%' stepped from 2 to 3 at incident time, recording the flag configuration change that activated the 50% payment failure rate", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "The metric holds steady at 2 from 20:32 through 20:53. At 20:54 it jumps to 3 and remains there, which is the first timestamp after the incident time (20:52:46) showing a clear rise above the baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_service": "oteldemo.CheckoutService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.CheckoutService\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout gRPC server calls returning Internal (code 13) status increased as payment failures propagate through checkout's PlaceOrder handler which returns codes.Internal when chargeCard fails", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (0 to ~0.00417). After the incident at 20:52:46, the metric jumps to 0.00833 at 20:54 — double the previous max baseline value — and continues rising to a peak of ~0.0208 at 21:00, confirming a clear spike. 20:54 is the first post-incident timestamp with a sustained elevated value." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "Ccb3tp0Br_RFnSwRwgM9", + "@timestamp": "20:53:03.061" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "A8b3tp0Br_RFnSwR4QTz", + "@timestamp": "20:53:11.157" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OMb6tp0Br_RFnSwRkQw4", + "@timestamp": "20:56:07.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcb6tp0Br_RFnSwR6w2J", + "@timestamp": "20:56:30.579" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "jcb7tp0Br_RFnSwRHg5O", + "@timestamp": "20:56:43.267" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "zMb8tp0Br_RFnSwRJxHB", + "@timestamp": "20:57:51.593" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "tcb8tp0Br_RFnSwRyxPZ", + "@timestamp": "20:58:33.292" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "TMb_tp0Br_RFnSwRLRpT", + "@timestamp": "21:01:09.017" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "osYAt50Br_RFnSwREBxE", + "@timestamp": "21:02:07.788" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–43ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tsb3tp0Br_RFnSwR1gNn", + "@timestamp": "20:53:03.104" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "iMb3tp0Br_RFnSwR9QTa", + "@timestamp": "20:53:11.181" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "08b6tp0Br_RFnSwRpQza", + "@timestamp": "20:56:07.671" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Pcb6tp0Br_RFnSwR_w7i", + "@timestamp": "20:56:30.622" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "CMb7tp0Br_RFnSwRMg_c", + "@timestamp": "20:56:43.293" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "UMb8tp0Br_RFnSwRPBLk", + "@timestamp": "20:57:51.613" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Gcb8tp0Br_RFnSwR4RQw", + "@timestamp": "20:58:33.317" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "icb_tp0Br_RFnSwRPhry", + "@timestamp": "21:01:09.047" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "VsYAt50Br_RFnSwRJR2k", + "@timestamp": "21:02:07.828" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:53:02 and 21:02:07 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "66b9ba801adf9f9f422434a778f79537", + "@timestamp": "20:53:02", + "user_action": "user_checkout_multi" + }, + { + "traceID": "72837353452f8a345bec058d3d020268", + "@timestamp": "20:53:11", + "user_action": "user_checkout_single" + }, + { + "traceID": "f255f946901777cd31f6d12a5f098a9e", + "@timestamp": "20:56:07", + "user_action": "user_checkout_single" + }, + { + "traceID": "f45d35ba65bccb4c4978380da5646dbc", + "@timestamp": "20:56:30", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b206613c795a05a3544ea6896b7691b", + "@timestamp": "20:56:43", + "user_action": "user_checkout_single" + }, + { + "traceID": "ad89464077ece735dd371b3d222a868d", + "@timestamp": "20:57:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "f394303704028931b06bfd39a4597301", + "@timestamp": "20:58:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "e021d85134fb82acc1f87a9e52abaf43", + "@timestamp": "21:01:08", + "user_action": "user_checkout_single" + }, + { + "traceID": "804e3624540aa57a66685981d6aa655a", + "@timestamp": "21:02:07", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cffa8510af04230dcb573fbf0b4f7aa4adf8d972 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json @@ -0,0 +1,357 @@ +{ + "incident_time": "2026-04-22T21:22:52.483960+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "0", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"0\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "Successful (OK) gRPC Charge calls from checkout to payment dropped to zero because the gRPC client is directed at badAddress:50051 which fails DNS resolution", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "Pre-incident, the metric oscillates between ~0.004 and ~0.017 with typical values around 0.008. After the incident at 21:22:52, the value at 21:23 is 0.00417 (still within normal range), then 21:24 shows 0.00417 as the last non-zero reading. From 21:25 onward the signal drops to zero and never recovers. The onset is 21:24 — the last timestamp showing pre-incident activity before the collapse." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "14", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"14\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "New gRPC UNAVAILABLE (code 14) errors appeared on checkout's client calls to PaymentService/Charge — the gRPC dial to badAddress:50051 fails with DNS resolution error", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric is flat at 0 from 21:02 through 21:23 (including the incident marker). At 21:24 it jumps to 0.00417, the first non-zero value, and continues rising steadily thereafter. This is the clear onset of the spike." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "propagation", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate", + "description": "Kafka consumer byte consumption rate dropped to zero because no order records are being produced to the orders topic, leaving the fraud-detection consumer with nothing to consume", + "onset_utc": "2026-04-22 21:21:00 UTC", + "onset_offset_seconds": -112, + "onset_reasoning": "Pre-incident pattern shows periodic non-zero values every 1-3 minutes (9.25, 9.54, 5.48, 8.7, 4.08, 4.35, 4.51, 4.27, 4.95). The last non-zero value is at 21:21 (4.9464). From 21:22 onward the signal is permanently zero, aligning with the incident at 21:22:52. This is the last active timestamp before the collapse." + } + ] + }, + { + "metric_family": "app_confirmation_counter", + "signal_layer": "symptom", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_confirmation_counter_total[5m])", + "description": "Checkout order confirmation rate dropped to zero because every checkout fails at the payment step, so no order confirmation emails are sent", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low but non-zero activity (oscillating around 0.004-0.017) before the incident. At 21:24 the value is 0.00416642, and from 21:25 onward it drops to zero permanently. The last non-trivial value is at 21:24, marking the final moment the pre-incident pattern is still active before the signal collapses." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "type": "log" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\", type=\"log\"}[5m])", + "description": "OTLP exporter record counter for logs exported by the fraud-detection service. Collapsed to zero because fraud-detection produces no order-processing logs when no orders arrive via Kafka.", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low-level periodic activity (oscillating roughly 0.004–0.017) before the incident. At 21:24 the value is 0.00416667, and from 21:25 onward it drops to 0 permanently. So 21:24 is the last timestamp with non-zero activity before the signal collapses, aligning closely with the incident time of 21:22:52." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-22T21:22:56.660Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 372 21 37 36 \"-\" \"python-requests/2.32.5\" \"39765a6c-ead4-9254-b089-6d267091fe68\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:60672 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "zMYTt50Br_RFnSwRIFmm", + "@timestamp": "21:22:56.660" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "q8YTt50Br_RFnSwRuVsu", + "@timestamp": "21:23:36.192" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OsYTt50Br_RFnSwR2Fxc", + "@timestamp": "21:23:43.528" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYUt50Br_RFnSwRt18x", + "@timestamp": "21:24:40.599" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "JMYVt50Br_RFnSwRU2G7", + "@timestamp": "21:25:21.132" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "b8YVt50Br_RFnSwRW2GB", + "@timestamp": "21:25:23.001" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cYVt50Br_RFnSwR6GM2", + "@timestamp": "21:25:59.000" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "bMYWt50Br_RFnSwROmVG", + "@timestamp": "21:26:19.473" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "58YWt50Br_RFnSwRv2Yb", + "@timestamp": "21:26:53.885" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYWt50Br_RFnSwRxmfp", + "@timestamp": "21:26:55.839" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "mMYWt50Br_RFnSwR1meH", + "@timestamp": "21:26:59.477" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "NMYXt50Br_RFnSwRfmmP", + "@timestamp": "21:27:43.350" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "FMYXt50Br_RFnSwRoWqt", + "@timestamp": "21:27:51.861" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "f8YXt50Br_RFnSwR92um", + "@timestamp": "21:28:13.953" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcYZt50Br_RFnSwRmW_c", + "@timestamp": "21:30:01.382" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yat50Br_RFnSwRA3BZ", + "@timestamp": "21:30:28.410" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ScYat50Br_RFnSwRHnG2", + "@timestamp": "21:30:35.254" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ksYat50Br_RFnSwRwnPN", + "@timestamp": "21:31:17.237" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ocYbt50Br_RFnSwRW3Us", + "@timestamp": "21:31:55.636" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "isYct50Br_RFnSwRCnj5", + "@timestamp": "21:32:40.871" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yct50Br_RFnSwRGniZ", + "@timestamp": "21:32:45.287" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "ef1830bae2b06545f2a0ce5082b28603", + "@timestamp": "21:22:56", + "user_action": "user_checkout_multi" + }, + { + "traceID": "9ba2397f2ded4d7ece094390cdab35e5", + "@timestamp": "21:23:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "2f408f49c74e7eea3612ef826f10f421", + "@timestamp": "21:23:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "096d4942de145bb342e6959b152b52e0", + "@timestamp": "21:24:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a8a4d188026cbf1bf78b0dabde9662e2", + "@timestamp": "21:25:21", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f14a727ca1de784762fdc8d49a788989", + "@timestamp": "21:25:22", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7f40ec3e191d9be6b09396b5194f21de", + "@timestamp": "21:25:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6e725c6b333de8026b05a16bf7f4a619", + "@timestamp": "21:26:19", + "user_action": "user_checkout_single" + }, + { + "traceID": "8f64663d763e5607f2943043aadcd53d", + "@timestamp": "21:26:53", + "user_action": "user_checkout_single" + }, + { + "traceID": "d6fe178e3ac626e359d37e4a18bf4f71", + "@timestamp": "21:26:55", + "user_action": "user_checkout_single" + }, + { + "traceID": "0a0f9239ebb6afdd0015c315c816b4a1", + "@timestamp": "21:26:59", + "user_action": "user_checkout_single" + }, + { + "traceID": "4e3bb300c7f158ff428414804727359e", + "@timestamp": "21:27:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cca1ebb62eca649ce47b9c0d64b186d1", + "@timestamp": "21:27:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "accdadceaf5af68cf0be327155f9f2ac", + "@timestamp": "21:28:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "6a7beb8972f9e43fffb874210034c9d3", + "@timestamp": "21:30:01", + "user_action": "user_checkout_single" + }, + { + "traceID": "9039f2ae7a68223da4113f72eb81dc83", + "@timestamp": "21:30:28", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5dcb2636f02200ebe76974ae944c1965", + "@timestamp": "21:30:35", + "user_action": "user_checkout_single" + }, + { + "traceID": "5ef605bd79cfb4907d80db49d4e57701", + "@timestamp": "21:31:17", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e05f457e54ebfb886701005b1c90734a", + "@timestamp": "21:31:55", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b0f522f893442746d64bfab844df9c7", + "@timestamp": "21:32:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fee034208640c0d39ee49e002446fa52", + "@timestamp": "21:32:45", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/test.sh b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d4-d3dep-paymentfailure-50-03-medium_ttd60m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..cffa8510af04230dcb573fbf0b4f7aa4adf8d972 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,357 @@ +{ + "incident_time": "2026-04-22T21:22:52.483960+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "0", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"0\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "Successful (OK) gRPC Charge calls from checkout to payment dropped to zero because the gRPC client is directed at badAddress:50051 which fails DNS resolution", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "Pre-incident, the metric oscillates between ~0.004 and ~0.017 with typical values around 0.008. After the incident at 21:22:52, the value at 21:23 is 0.00417 (still within normal range), then 21:24 shows 0.00417 as the last non-zero reading. From 21:25 onward the signal drops to zero and never recovers. The onset is 21:24 — the last timestamp showing pre-incident activity before the collapse." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "14", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"14\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "New gRPC UNAVAILABLE (code 14) errors appeared on checkout's client calls to PaymentService/Charge — the gRPC dial to badAddress:50051 fails with DNS resolution error", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric is flat at 0 from 21:02 through 21:23 (including the incident marker). At 21:24 it jumps to 0.00417, the first non-zero value, and continues rising steadily thereafter. This is the clear onset of the spike." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "propagation", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate", + "description": "Kafka consumer byte consumption rate dropped to zero because no order records are being produced to the orders topic, leaving the fraud-detection consumer with nothing to consume", + "onset_utc": "2026-04-22 21:21:00 UTC", + "onset_offset_seconds": -112, + "onset_reasoning": "Pre-incident pattern shows periodic non-zero values every 1-3 minutes (9.25, 9.54, 5.48, 8.7, 4.08, 4.35, 4.51, 4.27, 4.95). The last non-zero value is at 21:21 (4.9464). From 21:22 onward the signal is permanently zero, aligning with the incident at 21:22:52. This is the last active timestamp before the collapse." + } + ] + }, + { + "metric_family": "app_confirmation_counter", + "signal_layer": "symptom", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_confirmation_counter_total[5m])", + "description": "Checkout order confirmation rate dropped to zero because every checkout fails at the payment step, so no order confirmation emails are sent", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low but non-zero activity (oscillating around 0.004-0.017) before the incident. At 21:24 the value is 0.00416642, and from 21:25 onward it drops to zero permanently. The last non-trivial value is at 21:24, marking the final moment the pre-incident pattern is still active before the signal collapses." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "type": "log" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\", type=\"log\"}[5m])", + "description": "OTLP exporter record counter for logs exported by the fraud-detection service. Collapsed to zero because fraud-detection produces no order-processing logs when no orders arrive via Kafka.", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low-level periodic activity (oscillating roughly 0.004–0.017) before the incident. At 21:24 the value is 0.00416667, and from 21:25 onward it drops to 0 permanently. So 21:24 is the last timestamp with non-zero activity before the signal collapses, aligning closely with the incident time of 21:22:52." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-22T21:22:56.660Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 372 21 37 36 \"-\" \"python-requests/2.32.5\" \"39765a6c-ead4-9254-b089-6d267091fe68\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:60672 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "zMYTt50Br_RFnSwRIFmm", + "@timestamp": "21:22:56.660" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "q8YTt50Br_RFnSwRuVsu", + "@timestamp": "21:23:36.192" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OsYTt50Br_RFnSwR2Fxc", + "@timestamp": "21:23:43.528" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYUt50Br_RFnSwRt18x", + "@timestamp": "21:24:40.599" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "JMYVt50Br_RFnSwRU2G7", + "@timestamp": "21:25:21.132" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "b8YVt50Br_RFnSwRW2GB", + "@timestamp": "21:25:23.001" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cYVt50Br_RFnSwR6GM2", + "@timestamp": "21:25:59.000" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "bMYWt50Br_RFnSwROmVG", + "@timestamp": "21:26:19.473" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "58YWt50Br_RFnSwRv2Yb", + "@timestamp": "21:26:53.885" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYWt50Br_RFnSwRxmfp", + "@timestamp": "21:26:55.839" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "mMYWt50Br_RFnSwR1meH", + "@timestamp": "21:26:59.477" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "NMYXt50Br_RFnSwRfmmP", + "@timestamp": "21:27:43.350" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "FMYXt50Br_RFnSwRoWqt", + "@timestamp": "21:27:51.861" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "f8YXt50Br_RFnSwR92um", + "@timestamp": "21:28:13.953" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcYZt50Br_RFnSwRmW_c", + "@timestamp": "21:30:01.382" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yat50Br_RFnSwRA3BZ", + "@timestamp": "21:30:28.410" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ScYat50Br_RFnSwRHnG2", + "@timestamp": "21:30:35.254" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ksYat50Br_RFnSwRwnPN", + "@timestamp": "21:31:17.237" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ocYbt50Br_RFnSwRW3Us", + "@timestamp": "21:31:55.636" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "isYct50Br_RFnSwRCnj5", + "@timestamp": "21:32:40.871" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yct50Br_RFnSwRGniZ", + "@timestamp": "21:32:45.287" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "ef1830bae2b06545f2a0ce5082b28603", + "@timestamp": "21:22:56", + "user_action": "user_checkout_multi" + }, + { + "traceID": "9ba2397f2ded4d7ece094390cdab35e5", + "@timestamp": "21:23:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "2f408f49c74e7eea3612ef826f10f421", + "@timestamp": "21:23:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "096d4942de145bb342e6959b152b52e0", + "@timestamp": "21:24:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a8a4d188026cbf1bf78b0dabde9662e2", + "@timestamp": "21:25:21", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f14a727ca1de784762fdc8d49a788989", + "@timestamp": "21:25:22", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7f40ec3e191d9be6b09396b5194f21de", + "@timestamp": "21:25:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6e725c6b333de8026b05a16bf7f4a619", + "@timestamp": "21:26:19", + "user_action": "user_checkout_single" + }, + { + "traceID": "8f64663d763e5607f2943043aadcd53d", + "@timestamp": "21:26:53", + "user_action": "user_checkout_single" + }, + { + "traceID": "d6fe178e3ac626e359d37e4a18bf4f71", + "@timestamp": "21:26:55", + "user_action": "user_checkout_single" + }, + { + "traceID": "0a0f9239ebb6afdd0015c315c816b4a1", + "@timestamp": "21:26:59", + "user_action": "user_checkout_single" + }, + { + "traceID": "4e3bb300c7f158ff428414804727359e", + "@timestamp": "21:27:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cca1ebb62eca649ce47b9c0d64b186d1", + "@timestamp": "21:27:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "accdadceaf5af68cf0be327155f9f2ac", + "@timestamp": "21:28:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "6a7beb8972f9e43fffb874210034c9d3", + "@timestamp": "21:30:01", + "user_action": "user_checkout_single" + }, + { + "traceID": "9039f2ae7a68223da4113f72eb81dc83", + "@timestamp": "21:30:28", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5dcb2636f02200ebe76974ae944c1965", + "@timestamp": "21:30:35", + "user_action": "user_checkout_single" + }, + { + "traceID": "5ef605bd79cfb4907d80db49d4e57701", + "@timestamp": "21:31:17", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e05f457e54ebfb886701005b1c90734a", + "@timestamp": "21:31:55", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b0f522f893442746d64bfab844df9c7", + "@timestamp": "21:32:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fee034208640c0d39ee49e002446fa52", + "@timestamp": "21:32:45", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..e55cb50e5ea8db42bed372710d0f6b475b1f759c --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentFailure-10%.json @@ -0,0 +1,200 @@ +{ + "incident_time": "2026-04-22T20:22:41.236522+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the payment service's Charge RPC. Was zero before the incident; the paymentFailure flag causes ~10% of charge calls to throw, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram count for payment Charge errors. Was zero before the incident; each failed charge produces a duration sample in this histogram.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:28. The first non-zero value appears at 20:29 (0.00416667), which is about 6 minutes after the incident time. This is the clear onset of the spike above the zero baseline." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration sum for payment Charge errors. Was zero before the incident; tracks cumulative latency of failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00426, which is the first non-zero value after the incident time (20:22:41). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram buckets for payment Charge errors. Was zero before the incident; populates latency distribution buckets for failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The baseline is 0 throughout the pre-incident period. After the incident at 20:22:41 UTC, the metric remains at 0 until 20:29:00 UTC when it first spikes to 0.0708333, clearly rising above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": "2026-04-22 20:24:00 UTC", + "onset_offset_seconds": 78, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:23. At 20:24 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"checkout\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the checkout service's client-side PaymentService/Charge span. Was zero before the incident; errors from the payment service propagate as gRPC errors on the checkout side.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:27:53 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "IsXgtp0Br_RFnSwRubU5", + "@timestamp": "20:27:53.167" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:27:53 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "ksXgtp0Br_RFnSwRy7W0", + "@timestamp": "20:27:53.198" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:27:53 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2de5b0fee49445b07e09b4338ca9f884", + "@timestamp": "20:27:53", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7db86e578213a88b97fea945d9a0c0a8ac87bb --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentFailure-50%.json @@ -0,0 +1,301 @@ +{ + "incident_time": "2026-04-22T20:52:46.740910+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call rate for payment service's Charge RPC with error status. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, producing new STATUS_CODE_ERROR spans on the payment service.", + "onset_utc": "2026-04-22 20:55:00 UTC", + "onset_offset_seconds": 133, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors (~0.004 or 0) with many zero values. After the incident at 20:52:46, the metric jumps to 0.00833333 at 20:55:00 — roughly 2x the previous sporadic baseline — and sustains elevated values (0.008–0.02) from that point onward, indicating the clear start of the error spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_service": "oteldemo.PaymentService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_service=\"oteldemo.PaymentService\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC client calls to PaymentService/Charge returning Unknown (code 2) status spiked as the payment service throws errors when the paymentFailure flag triggers", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline oscillates between 0 and ~0.00417. After the incident at 20:52:46, the value at 20:54 jumps to 0.00833, which is 2x the baseline, and continues rising to a peak of ~0.0208 at 21:00. This is the first timestamp after the incident where the metric clearly exceeds the pre-incident range." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout requests returning HTTP 500 increased as the paymentFailure flag causes ~50% of payment charges to throw errors, which propagate through checkout as gRPC Internal errors and surface as HTTP 500 responses", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (~0.004) interspersed with zeros. After the incident at 20:52:46, the first post-incident nonzero value at 20:54 is 0.00833, which is ~2x the baseline sporadic value, and it sustains and climbs further (0.0125, 0.0167, 0.0208), confirming a clear spike onset at 20:54." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag with variant '50%' stepped from 2 to 3 at incident time, recording the flag configuration change that activated the 50% payment failure rate", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "The metric holds steady at 2 from 20:32 through 20:53. At 20:54 it jumps to 3 and remains there, which is the first timestamp after the incident time (20:52:46) showing a clear rise above the baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_service": "oteldemo.CheckoutService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.CheckoutService\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout gRPC server calls returning Internal (code 13) status increased as payment failures propagate through checkout's PlaceOrder handler which returns codes.Internal when chargeCard fails", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (0 to ~0.00417). After the incident at 20:52:46, the metric jumps to 0.00833 at 20:54 — double the previous max baseline value — and continues rising to a peak of ~0.0208 at 21:00, confirming a clear spike. 20:54 is the first post-incident timestamp with a sustained elevated value." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "Ccb3tp0Br_RFnSwRwgM9", + "@timestamp": "20:53:03.061" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "A8b3tp0Br_RFnSwR4QTz", + "@timestamp": "20:53:11.157" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OMb6tp0Br_RFnSwRkQw4", + "@timestamp": "20:56:07.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcb6tp0Br_RFnSwR6w2J", + "@timestamp": "20:56:30.579" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "jcb7tp0Br_RFnSwRHg5O", + "@timestamp": "20:56:43.267" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "zMb8tp0Br_RFnSwRJxHB", + "@timestamp": "20:57:51.593" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "tcb8tp0Br_RFnSwRyxPZ", + "@timestamp": "20:58:33.292" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "TMb_tp0Br_RFnSwRLRpT", + "@timestamp": "21:01:09.017" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "osYAt50Br_RFnSwREBxE", + "@timestamp": "21:02:07.788" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–43ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tsb3tp0Br_RFnSwR1gNn", + "@timestamp": "20:53:03.104" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "iMb3tp0Br_RFnSwR9QTa", + "@timestamp": "20:53:11.181" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "08b6tp0Br_RFnSwRpQza", + "@timestamp": "20:56:07.671" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Pcb6tp0Br_RFnSwR_w7i", + "@timestamp": "20:56:30.622" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "CMb7tp0Br_RFnSwRMg_c", + "@timestamp": "20:56:43.293" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "UMb8tp0Br_RFnSwRPBLk", + "@timestamp": "20:57:51.613" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Gcb8tp0Br_RFnSwR4RQw", + "@timestamp": "20:58:33.317" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "icb_tp0Br_RFnSwRPhry", + "@timestamp": "21:01:09.047" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "VsYAt50Br_RFnSwRJR2k", + "@timestamp": "21:02:07.828" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:53:02 and 21:02:07 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "66b9ba801adf9f9f422434a778f79537", + "@timestamp": "20:53:02", + "user_action": "user_checkout_multi" + }, + { + "traceID": "72837353452f8a345bec058d3d020268", + "@timestamp": "20:53:11", + "user_action": "user_checkout_single" + }, + { + "traceID": "f255f946901777cd31f6d12a5f098a9e", + "@timestamp": "20:56:07", + "user_action": "user_checkout_single" + }, + { + "traceID": "f45d35ba65bccb4c4978380da5646dbc", + "@timestamp": "20:56:30", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b206613c795a05a3544ea6896b7691b", + "@timestamp": "20:56:43", + "user_action": "user_checkout_single" + }, + { + "traceID": "ad89464077ece735dd371b3d222a868d", + "@timestamp": "20:57:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "f394303704028931b06bfd39a4597301", + "@timestamp": "20:58:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "e021d85134fb82acc1f87a9e52abaf43", + "@timestamp": "21:01:08", + "user_action": "user_checkout_single" + }, + { + "traceID": "804e3624540aa57a66685981d6aa655a", + "@timestamp": "21:02:07", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cffa8510af04230dcb573fbf0b4f7aa4adf8d972 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-paymentUnreachable-on.json @@ -0,0 +1,357 @@ +{ + "incident_time": "2026-04-22T21:22:52.483960+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "0", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"0\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "Successful (OK) gRPC Charge calls from checkout to payment dropped to zero because the gRPC client is directed at badAddress:50051 which fails DNS resolution", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "Pre-incident, the metric oscillates between ~0.004 and ~0.017 with typical values around 0.008. After the incident at 21:22:52, the value at 21:23 is 0.00417 (still within normal range), then 21:24 shows 0.00417 as the last non-zero reading. From 21:25 onward the signal drops to zero and never recovers. The onset is 21:24 — the last timestamp showing pre-incident activity before the collapse." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "14", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"14\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "New gRPC UNAVAILABLE (code 14) errors appeared on checkout's client calls to PaymentService/Charge — the gRPC dial to badAddress:50051 fails with DNS resolution error", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric is flat at 0 from 21:02 through 21:23 (including the incident marker). At 21:24 it jumps to 0.00417, the first non-zero value, and continues rising steadily thereafter. This is the clear onset of the spike." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "propagation", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate", + "description": "Kafka consumer byte consumption rate dropped to zero because no order records are being produced to the orders topic, leaving the fraud-detection consumer with nothing to consume", + "onset_utc": "2026-04-22 21:21:00 UTC", + "onset_offset_seconds": -112, + "onset_reasoning": "Pre-incident pattern shows periodic non-zero values every 1-3 minutes (9.25, 9.54, 5.48, 8.7, 4.08, 4.35, 4.51, 4.27, 4.95). The last non-zero value is at 21:21 (4.9464). From 21:22 onward the signal is permanently zero, aligning with the incident at 21:22:52. This is the last active timestamp before the collapse." + } + ] + }, + { + "metric_family": "app_confirmation_counter", + "signal_layer": "symptom", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_confirmation_counter_total[5m])", + "description": "Checkout order confirmation rate dropped to zero because every checkout fails at the payment step, so no order confirmation emails are sent", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low but non-zero activity (oscillating around 0.004-0.017) before the incident. At 21:24 the value is 0.00416642, and from 21:25 onward it drops to zero permanently. The last non-trivial value is at 21:24, marking the final moment the pre-incident pattern is still active before the signal collapses." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "type": "log" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\", type=\"log\"}[5m])", + "description": "OTLP exporter record counter for logs exported by the fraud-detection service. Collapsed to zero because fraud-detection produces no order-processing logs when no orders arrive via Kafka.", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low-level periodic activity (oscillating roughly 0.004–0.017) before the incident. At 21:24 the value is 0.00416667, and from 21:25 onward it drops to 0 permanently. So 21:24 is the last timestamp with non-zero activity before the signal collapses, aligning closely with the incident time of 21:22:52." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-22T21:22:56.660Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 372 21 37 36 \"-\" \"python-requests/2.32.5\" \"39765a6c-ead4-9254-b089-6d267091fe68\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:60672 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "zMYTt50Br_RFnSwRIFmm", + "@timestamp": "21:22:56.660" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "q8YTt50Br_RFnSwRuVsu", + "@timestamp": "21:23:36.192" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OsYTt50Br_RFnSwR2Fxc", + "@timestamp": "21:23:43.528" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYUt50Br_RFnSwRt18x", + "@timestamp": "21:24:40.599" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "JMYVt50Br_RFnSwRU2G7", + "@timestamp": "21:25:21.132" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "b8YVt50Br_RFnSwRW2GB", + "@timestamp": "21:25:23.001" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cYVt50Br_RFnSwR6GM2", + "@timestamp": "21:25:59.000" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "bMYWt50Br_RFnSwROmVG", + "@timestamp": "21:26:19.473" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "58YWt50Br_RFnSwRv2Yb", + "@timestamp": "21:26:53.885" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYWt50Br_RFnSwRxmfp", + "@timestamp": "21:26:55.839" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "mMYWt50Br_RFnSwR1meH", + "@timestamp": "21:26:59.477" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "NMYXt50Br_RFnSwRfmmP", + "@timestamp": "21:27:43.350" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "FMYXt50Br_RFnSwRoWqt", + "@timestamp": "21:27:51.861" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "f8YXt50Br_RFnSwR92um", + "@timestamp": "21:28:13.953" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcYZt50Br_RFnSwRmW_c", + "@timestamp": "21:30:01.382" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yat50Br_RFnSwRA3BZ", + "@timestamp": "21:30:28.410" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ScYat50Br_RFnSwRHnG2", + "@timestamp": "21:30:35.254" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ksYat50Br_RFnSwRwnPN", + "@timestamp": "21:31:17.237" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ocYbt50Br_RFnSwRW3Us", + "@timestamp": "21:31:55.636" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "isYct50Br_RFnSwRCnj5", + "@timestamp": "21:32:40.871" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yct50Br_RFnSwRGniZ", + "@timestamp": "21:32:45.287" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "ef1830bae2b06545f2a0ce5082b28603", + "@timestamp": "21:22:56", + "user_action": "user_checkout_multi" + }, + { + "traceID": "9ba2397f2ded4d7ece094390cdab35e5", + "@timestamp": "21:23:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "2f408f49c74e7eea3612ef826f10f421", + "@timestamp": "21:23:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "096d4942de145bb342e6959b152b52e0", + "@timestamp": "21:24:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a8a4d188026cbf1bf78b0dabde9662e2", + "@timestamp": "21:25:21", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f14a727ca1de784762fdc8d49a788989", + "@timestamp": "21:25:22", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7f40ec3e191d9be6b09396b5194f21de", + "@timestamp": "21:25:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6e725c6b333de8026b05a16bf7f4a619", + "@timestamp": "21:26:19", + "user_action": "user_checkout_single" + }, + { + "traceID": "8f64663d763e5607f2943043aadcd53d", + "@timestamp": "21:26:53", + "user_action": "user_checkout_single" + }, + { + "traceID": "d6fe178e3ac626e359d37e4a18bf4f71", + "@timestamp": "21:26:55", + "user_action": "user_checkout_single" + }, + { + "traceID": "0a0f9239ebb6afdd0015c315c816b4a1", + "@timestamp": "21:26:59", + "user_action": "user_checkout_single" + }, + { + "traceID": "4e3bb300c7f158ff428414804727359e", + "@timestamp": "21:27:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cca1ebb62eca649ce47b9c0d64b186d1", + "@timestamp": "21:27:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "accdadceaf5af68cf0be327155f9f2ac", + "@timestamp": "21:28:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "6a7beb8972f9e43fffb874210034c9d3", + "@timestamp": "21:30:01", + "user_action": "user_checkout_single" + }, + { + "traceID": "9039f2ae7a68223da4113f72eb81dc83", + "@timestamp": "21:30:28", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5dcb2636f02200ebe76974ae944c1965", + "@timestamp": "21:30:35", + "user_action": "user_checkout_single" + }, + { + "traceID": "5ef605bd79cfb4907d80db49d4e57701", + "@timestamp": "21:31:17", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e05f457e54ebfb886701005b1c90734a", + "@timestamp": "21:31:55", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b0f522f893442746d64bfab844df9c7", + "@timestamp": "21:32:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fee034208640c0d39ee49e002446fa52", + "@timestamp": "21:32:45", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..00bdecb1076512e6a2506af53ae4fc12575fcee6 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d4-d3dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-22T21:22:52.483960+00:00" + }, + { + "event_id": "d4-d3dep-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-22T18:52:17.653473+00:00" + }, + { + "event_id": "d4-d3dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-22T20:22:41.236522+00:00" + }, + { + "event_id": "d4-d3dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-22T20:52:46.740910+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..e55cb50e5ea8db42bed372710d0f6b475b1f759c --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentFailure-10%.json @@ -0,0 +1,200 @@ +{ + "incident_time": "2026-04-22T20:22:41.236522+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the payment service's Charge RPC. Was zero before the incident; the paymentFailure flag causes ~10% of charge calls to throw, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram count for payment Charge errors. Was zero before the incident; each failed charge produces a duration sample in this histogram.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:28. The first non-zero value appears at 20:29 (0.00416667), which is about 6 minutes after the incident time. This is the clear onset of the spike above the zero baseline." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration sum for payment Charge errors. Was zero before the incident; tracks cumulative latency of failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00426, which is the first non-zero value after the incident time (20:22:41). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"payment\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error duration histogram buckets for payment Charge errors. Was zero before the incident; populates latency distribution buckets for failed charge spans.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The baseline is 0 throughout the pre-incident period. After the incident at 20:22:41 UTC, the metric remains at 0 until 20:29:00 UTC when it first spikes to 0.0708333, clearly rising above the zero baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\",service_name=\"checkout\"}[5m])", + "description": "gRPC client errors (UNKNOWN/code 2) from checkout calling payment Charge method — new series that appeared after the paymentFailure flag was enabled, representing the 10% of charge requests that throw 'Payment request failed. Invalid token'", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it first rises to ~0.00417, which is the first clear spike above the zero baseline after the incident time (20:22:41 UTC)." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded a new impression for the paymentFailure flag with variant '10%' — this time series did not exist before the flag was turned on, confirming the flag evaluation changed from 'off' to '10%'", + "onset_utc": "2026-04-22 20:24:00 UTC", + "onset_offset_seconds": 78, + "onset_reasoning": "The metric is flat at 0 from 20:02 through 20:23. At 20:24 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "sum(rate(traces_span_metrics_calls_total{service_name=\"checkout\", status_code=\"STATUS_CODE_ERROR\", span_name=\"oteldemo.PaymentService/Charge\"}[5m]))", + "description": "Span-derived error call counter for the checkout service's client-side PaymentService/Charge span. Was zero before the incident; errors from the payment service propagate as gRPC errors on the checkout side.", + "onset_utc": "2026-04-22 20:29:00 UTC", + "onset_offset_seconds": 378, + "onset_reasoning": "The metric is flat at 0 from the start of the series through 20:28. At 20:29 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:22:41). This marks the onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "At 20:27:53 UTC, 1 Envoy access log entry shows POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "IsXgtp0Br_RFnSwRubU5", + "@timestamp": "20:27:53.167" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "At 20:27:53 UTC, 1 payment service warn-level log records the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 31ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "ksXgtp0Br_RFnSwRy7W0", + "@timestamp": "20:27:53.198" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "At 20:27:53 UTC, 1 trace shows checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2de5b0fee49445b07e09b4338ca9f884", + "@timestamp": "20:27:53", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7db86e578213a88b97fea945d9a0c0a8ac87bb --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentFailure-50%.json @@ -0,0 +1,301 @@ +{ + "incident_time": "2026-04-22T20:52:46.740910+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call rate for payment service's Charge RPC with error status. The paymentFailure flag causes charge.js to throw 'Payment request failed' with 50% probability, producing new STATUS_CODE_ERROR spans on the payment service.", + "onset_utc": "2026-04-22 20:55:00 UTC", + "onset_offset_seconds": 133, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors (~0.004 or 0) with many zero values. After the incident at 20:52:46, the metric jumps to 0.00833333 at 20:55:00 — roughly 2x the previous sporadic baseline — and sustains elevated values (0.008–0.02) from that point onward, indicating the clear start of the error spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_service": "oteldemo.PaymentService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_service=\"oteldemo.PaymentService\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's gRPC client calls to PaymentService/Charge returning Unknown (code 2) status spiked as the payment service throws errors when the paymentFailure flag triggers", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline oscillates between 0 and ~0.00417. After the incident at 20:52:46, the value at 20:54 jumps to 0.00833, which is 2x the baseline, and continues rising to a peak of ~0.0208 at 21:00. This is the first timestamp after the incident where the metric clearly exceeds the pre-incident range." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout requests returning HTTP 500 increased as the paymentFailure flag causes ~50% of payment charges to throw errors, which propagate through checkout as gRPC Internal errors and surface as HTTP 500 responses", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (~0.004) interspersed with zeros. After the incident at 20:52:46, the first post-incident nonzero value at 20:54 is 0.00833, which is ~2x the baseline sporadic value, and it sustains and climbs further (0.0125, 0.0167, 0.0208), confirming a clear spike onset at 20:54." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}", + "description": "The flagd impression counter for the paymentFailure flag with variant '50%' stepped from 2 to 3 at incident time, recording the flag configuration change that activated the 50% payment failure rate", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "The metric holds steady at 2 from 20:32 through 20:53. At 20:54 it jumps to 3 and remains there, which is the first timestamp after the incident time (20:52:46) showing a clear rise above the baseline." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_service": "oteldemo.CheckoutService" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_service=\"oteldemo.CheckoutService\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout gRPC server calls returning Internal (code 13) status increased as payment failures propagate through checkout's PlaceOrder handler which returns codes.Internal when chargeCard fails", + "onset_utc": "2026-04-22 20:54:00 UTC", + "onset_offset_seconds": 73, + "onset_reasoning": "Pre-incident baseline shows sporadic low values (0 to ~0.00417). After the incident at 20:52:46, the metric jumps to 0.00833 at 20:54 — double the previous max baseline value — and continues rising to a peak of ~0.0208 at 21:00, confirming a clear spike. 20:54 is the first post-incident timestamp with a sustained elevated value." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "Ccb3tp0Br_RFnSwRwgM9", + "@timestamp": "20:53:03.061" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "A8b3tp0Br_RFnSwR4QTz", + "@timestamp": "20:53:11.157" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OMb6tp0Br_RFnSwRkQw4", + "@timestamp": "20:56:07.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcb6tp0Br_RFnSwR6w2J", + "@timestamp": "20:56:30.579" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "jcb7tp0Br_RFnSwRHg5O", + "@timestamp": "20:56:43.267" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "zMb8tp0Br_RFnSwRJxHB", + "@timestamp": "20:57:51.593" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "tcb8tp0Br_RFnSwRyxPZ", + "@timestamp": "20:58:33.292" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "TMb_tp0Br_RFnSwRLRpT", + "@timestamp": "21:01:09.017" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "osYAt50Br_RFnSwREBxE", + "@timestamp": "21:02:07.788" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:53:03 and 21:02:07 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 19–43ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tsb3tp0Br_RFnSwR1gNn", + "@timestamp": "20:53:03.104" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "iMb3tp0Br_RFnSwR9QTa", + "@timestamp": "20:53:11.181" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "08b6tp0Br_RFnSwRpQza", + "@timestamp": "20:56:07.671" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Pcb6tp0Br_RFnSwR_w7i", + "@timestamp": "20:56:30.622" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "CMb7tp0Br_RFnSwRMg_c", + "@timestamp": "20:56:43.293" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "UMb8tp0Br_RFnSwRPBLk", + "@timestamp": "20:57:51.613" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "Gcb8tp0Br_RFnSwR4RQw", + "@timestamp": "20:58:33.317" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "icb_tp0Br_RFnSwRPhry", + "@timestamp": "21:01:09.047" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "VsYAt50Br_RFnSwRJR2k", + "@timestamp": "21:02:07.828" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:53:02 and 21:02:07 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "66b9ba801adf9f9f422434a778f79537", + "@timestamp": "20:53:02", + "user_action": "user_checkout_multi" + }, + { + "traceID": "72837353452f8a345bec058d3d020268", + "@timestamp": "20:53:11", + "user_action": "user_checkout_single" + }, + { + "traceID": "f255f946901777cd31f6d12a5f098a9e", + "@timestamp": "20:56:07", + "user_action": "user_checkout_single" + }, + { + "traceID": "f45d35ba65bccb4c4978380da5646dbc", + "@timestamp": "20:56:30", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b206613c795a05a3544ea6896b7691b", + "@timestamp": "20:56:43", + "user_action": "user_checkout_single" + }, + { + "traceID": "ad89464077ece735dd371b3d222a868d", + "@timestamp": "20:57:51", + "user_action": "user_checkout_single" + }, + { + "traceID": "f394303704028931b06bfd39a4597301", + "@timestamp": "20:58:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "e021d85134fb82acc1f87a9e52abaf43", + "@timestamp": "21:01:08", + "user_action": "user_checkout_single" + }, + { + "traceID": "804e3624540aa57a66685981d6aa655a", + "@timestamp": "21:02:07", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..cffa8510af04230dcb573fbf0b4f7aa4adf8d972 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-paymentUnreachable-on.json @@ -0,0 +1,357 @@ +{ + "incident_time": "2026-04-22T21:22:52.483960+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "0", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"0\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "Successful (OK) gRPC Charge calls from checkout to payment dropped to zero because the gRPC client is directed at badAddress:50051 which fails DNS resolution", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "Pre-incident, the metric oscillates between ~0.004 and ~0.017 with typical values around 0.008. After the incident at 21:22:52, the value at 21:23 is 0.00417 (still within normal range), then 21:24 shows 0.00417 as the last non-zero reading. From 21:25 onward the signal drops to zero and never recovers. The onset is 21:24 — the last timestamp showing pre-incident activity before the collapse." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "job": "opentelemetry-demo/checkout", + "rpc_grpc_status_code": "14", + "rpc_method": "Charge" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_grpc_status_code=\"14\",rpc_method=\"Charge\",job=\"opentelemetry-demo/checkout\"}[5m])", + "description": "New gRPC UNAVAILABLE (code 14) errors appeared on checkout's client calls to PaymentService/Charge — the gRPC dial to badAddress:50051 fails with DNS resolution error", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric is flat at 0 from 21:02 through 21:23 (including the incident marker). At 21:24 it jumps to 0.00417, the first non-zero value, and continues rising steadily thereafter. This is the clear onset of the spike." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "propagation", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate", + "description": "Kafka consumer byte consumption rate dropped to zero because no order records are being produced to the orders topic, leaving the fraud-detection consumer with nothing to consume", + "onset_utc": "2026-04-22 21:21:00 UTC", + "onset_offset_seconds": -112, + "onset_reasoning": "Pre-incident pattern shows periodic non-zero values every 1-3 minutes (9.25, 9.54, 5.48, 8.7, 4.08, 4.35, 4.51, 4.27, 4.95). The last non-zero value is at 21:21 (4.9464). From 21:22 onward the signal is permanently zero, aligning with the incident at 21:22:52. This is the last active timestamp before the collapse." + } + ] + }, + { + "metric_family": "app_confirmation_counter", + "signal_layer": "symptom", + "defining_labels": {}, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_confirmation_counter_total[5m])", + "description": "Checkout order confirmation rate dropped to zero because every checkout fails at the payment step, so no order confirmation emails are sent", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low but non-zero activity (oscillating around 0.004-0.017) before the incident. At 21:24 the value is 0.00416642, and from 21:25 onward it drops to zero permanently. The last non-trivial value is at 21:24, marking the final moment the pre-incident pattern is still active before the signal collapses." + } + ] + }, + { + "metric_family": "otlp_exporter_exported", + "signal_layer": "meta", + "defining_labels": { + "service_name": "fraud-detection", + "type": "log" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(otlp_exporter_exported_total{service_name=\"fraud-detection\", type=\"log\"}[5m])", + "description": "OTLP exporter record counter for logs exported by the fraud-detection service. Collapsed to zero because fraud-detection produces no order-processing logs when no orders arrive via Kafka.", + "onset_utc": "2026-04-22 21:24:00 UTC", + "onset_offset_seconds": 67, + "onset_reasoning": "The metric shows low-level periodic activity (oscillating roughly 0.004–0.017) before the incident. At 21:24 the value is 0.00416667, and from 21:25 onward it drops to 0 permanently. So 21:24 is the last timestamp with non-zero activity before the signal collapses, aligning closely with the incident time of 21:22:52." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-22T21:22:56.660Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 372 21 37 36 \"-\" \"python-requests/2.32.5\" \"39765a6c-ead4-9254-b089-6d267091fe68\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:60672 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "zMYTt50Br_RFnSwRIFmm", + "@timestamp": "21:22:56.660" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "q8YTt50Br_RFnSwRuVsu", + "@timestamp": "21:23:36.192" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "OsYTt50Br_RFnSwR2Fxc", + "@timestamp": "21:23:43.528" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYUt50Br_RFnSwRt18x", + "@timestamp": "21:24:40.599" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "JMYVt50Br_RFnSwRU2G7", + "@timestamp": "21:25:21.132" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "b8YVt50Br_RFnSwRW2GB", + "@timestamp": "21:25:23.001" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cYVt50Br_RFnSwR6GM2", + "@timestamp": "21:25:59.000" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "bMYWt50Br_RFnSwROmVG", + "@timestamp": "21:26:19.473" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "58YWt50Br_RFnSwRv2Yb", + "@timestamp": "21:26:53.885" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "HsYWt50Br_RFnSwRxmfp", + "@timestamp": "21:26:55.839" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "mMYWt50Br_RFnSwR1meH", + "@timestamp": "21:26:59.477" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "NMYXt50Br_RFnSwRfmmP", + "@timestamp": "21:27:43.350" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "FMYXt50Br_RFnSwRoWqt", + "@timestamp": "21:27:51.861" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "f8YXt50Br_RFnSwR92um", + "@timestamp": "21:28:13.953" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "kcYZt50Br_RFnSwRmW_c", + "@timestamp": "21:30:01.382" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yat50Br_RFnSwRA3BZ", + "@timestamp": "21:30:28.410" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ScYat50Br_RFnSwRHnG2", + "@timestamp": "21:30:35.254" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ksYat50Br_RFnSwRwnPN", + "@timestamp": "21:31:17.237" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ocYbt50Br_RFnSwRW3Us", + "@timestamp": "21:31:55.636" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "isYct50Br_RFnSwRCnj5", + "@timestamp": "21:32:40.871" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "w8Yct50Br_RFnSwRGniZ", + "@timestamp": "21:32:45.287" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:22:56 and 21:32:45 UTC, 21 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "ef1830bae2b06545f2a0ce5082b28603", + "@timestamp": "21:22:56", + "user_action": "user_checkout_multi" + }, + { + "traceID": "9ba2397f2ded4d7ece094390cdab35e5", + "@timestamp": "21:23:36", + "user_action": "user_checkout_single" + }, + { + "traceID": "2f408f49c74e7eea3612ef826f10f421", + "@timestamp": "21:23:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "096d4942de145bb342e6959b152b52e0", + "@timestamp": "21:24:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "a8a4d188026cbf1bf78b0dabde9662e2", + "@timestamp": "21:25:21", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f14a727ca1de784762fdc8d49a788989", + "@timestamp": "21:25:22", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7f40ec3e191d9be6b09396b5194f21de", + "@timestamp": "21:25:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "6e725c6b333de8026b05a16bf7f4a619", + "@timestamp": "21:26:19", + "user_action": "user_checkout_single" + }, + { + "traceID": "8f64663d763e5607f2943043aadcd53d", + "@timestamp": "21:26:53", + "user_action": "user_checkout_single" + }, + { + "traceID": "d6fe178e3ac626e359d37e4a18bf4f71", + "@timestamp": "21:26:55", + "user_action": "user_checkout_single" + }, + { + "traceID": "0a0f9239ebb6afdd0015c315c816b4a1", + "@timestamp": "21:26:59", + "user_action": "user_checkout_single" + }, + { + "traceID": "4e3bb300c7f158ff428414804727359e", + "@timestamp": "21:27:43", + "user_action": "user_checkout_multi" + }, + { + "traceID": "cca1ebb62eca649ce47b9c0d64b186d1", + "@timestamp": "21:27:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "accdadceaf5af68cf0be327155f9f2ac", + "@timestamp": "21:28:13", + "user_action": "user_checkout_single" + }, + { + "traceID": "6a7beb8972f9e43fffb874210034c9d3", + "@timestamp": "21:30:01", + "user_action": "user_checkout_single" + }, + { + "traceID": "9039f2ae7a68223da4113f72eb81dc83", + "@timestamp": "21:30:28", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5dcb2636f02200ebe76974ae944c1965", + "@timestamp": "21:30:35", + "user_action": "user_checkout_single" + }, + { + "traceID": "5ef605bd79cfb4907d80db49d4e57701", + "@timestamp": "21:31:17", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e05f457e54ebfb886701005b1c90734a", + "@timestamp": "21:31:55", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3b0f522f893442746d64bfab844df9c7", + "@timestamp": "21:32:40", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fee034208640c0d39ee49e002446fa52", + "@timestamp": "21:32:45", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a4174ca6c904f7a16917e6d0ae7bd893c7f1aeb4 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/rubrics/d4-d3dep-productCatalogFailure-on.json @@ -0,0 +1,421 @@ +{ + "incident_time": "2026-04-22T18:52:17.653473+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side Internal (code 13) errors for GetProduct on the product-catalog service. The productCatalogFailure flag causes GetProduct to return status.Errorf(codes.Internal) for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it first rises to 0.00417, then steadily increases. This is the first non-zero value after the incident, marking the onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for product-catalog GetProduct errors. Spiked from 0 to ~0.03/s because the productCatalogFailure flag causes GetProduct to return codes.Internal for product OLJCESPC7Z.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline and remains 0 at 18:52 and 18:53. At 18:54 it first rises to 0.00417, then climbs steadily, marking the clear onset of the error-rate spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "method": "GET", + "status": "200", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_frontend_requests_total{status=\"200\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Successful (200) frontend requests for product OLJCESPC7Z dropped to zero. Every GetProduct call for OLJCESPC7Z fails once the flag is enabled, so no product page loads succeed.", + "onset_utc": "2026-04-22 18:53:00 UTC", + "onset_offset_seconds": 42, + "onset_reasoning": "The metric shows oscillating activity in the pre-incident period (values between ~0.004 and ~0.046). At 18:53 the value is 0.033, then at 18:54 it drops to 0.012, and from 18:55 onward it goes to zero permanently. The last timestamp with meaningful activity is 18:53, making it the onset where the pre-incident pattern ceases." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend-proxy", + "span_name": "GET", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend-proxy\", span_name=\"GET\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for frontend-proxy server-side errors. Spiked from 0 to ~0.03/s as the Envoy proxy observes 5xx responses from the frontend for product and recommendation requests.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then rapidly climbs to ~0.02-0.04 range and stays elevated. This is the first non-zero value after the incident, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "product-catalog", + "span_name": "oteldemo.ProductCatalogService/GetProduct", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration counter for product-catalog GetProduct. Spiked from 0 to ~0.03/s, tracking the latency distribution of failed GetProduct calls.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, then ramps up steadily. This is the first non-zero value after the incident, marking the clear onset of the error rate spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_bucket{service_name=\"product-catalog\", span_name=\"oteldemo.ProductCatalogService/GetProduct\", status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error duration histogram bucket for product-catalog GetProduct. All buckets spiked from 0 to ~0.03/s as error spans are recorded in the latency distribution.", + "onset_utc": "2026-04-22 18:54:00 UTC", + "onset_offset_seconds": 102, + "onset_reasoning": "The metric is flat at 0 from 18:32 through 18:53. At 18:54 it jumps to 0.00417, marking the first non-zero value after the incident. It then continues rising, confirming a sustained spike. This is the clear onset point, approximately 2 minutes after the incident injection at 18:52." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 18:53:01 and 19:01:54 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "tcSJtp0Br_RFnSwR34-Y", + "@timestamp": "18:53:01.623" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "c8SKtp0Br_RFnSwRIZD_", + "@timestamp": "18:53:18.703" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "scSKtp0Br_RFnSwRPZBs", + "@timestamp": "18:53:25.763" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "csSMtp0Br_RFnSwRb5j0", + "@timestamp": "18:55:49.530" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "l8SMtp0Br_RFnSwRyZnZ", + "@timestamp": "18:56:13.155" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "msSMtp0Br_RFnSwRzZm6", + "@timestamp": "18:56:14.098" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "5cSMtp0Br_RFnSwR_Jmp", + "@timestamp": "18:56:25.642" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "1sSOtp0Br_RFnSwRDpw_", + "@timestamp": "18:57:35.353" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "k8SOtp0Br_RFnSwRYJ1K", + "@timestamp": "18:57:56.978" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "pcSQtp0Br_RFnSwRyaWg", + "@timestamp": "19:00:35.024" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "ZMSRtp0Br_RFnSwRM6Yd", + "@timestamp": "19:01:01.443" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "YsSRtp0Br_RFnSwRWqcs", + "@timestamp": "19:01:11.713" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "QsSRtp0Br_RFnSwRrKgy", + "@timestamp": "19:01:33.234" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "_sSRtp0Br_RFnSwR_qhV", + "@timestamp": "19:01:54.260" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 18:54:02 and 19:01:23 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-22", + "_id": "jsSKtp0Br_RFnSwRypIS", + "@timestamp": "18:54:02.100" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "-MSLtp0Br_RFnSwRUpTR", + "@timestamp": "18:54:36.288" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "LsSMtp0Br_RFnSwRXJhs", + "@timestamp": "18:55:45.117" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "dMSMtp0Br_RFnSwRb5j_", + "@timestamp": "18:55:49.896" + }, + { + "_index": "otel-logs-2026-04-22", + "_id": "AMSRtp0Br_RFnSwRiagK", + "@timestamp": "19:01:23.738" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 18:53:01 and 19:01:54 UTC, 14 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_browse_product (13), user_add_to_cart (1). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "629260abd8dcaadbfd1df3d8de58eec4", + "@timestamp": "19:01:54", + "user_action": "user_browse_product" + }, + { + "traceID": "f1352a1a220580d1a959a7761492fd71", + "@timestamp": "19:01:33", + "user_action": "user_browse_product" + }, + { + "traceID": "f6f7510c5ca4929e0cea1b906018a21b", + "@timestamp": "19:01:11", + "user_action": "user_browse_product" + }, + { + "traceID": "868bb0df092f1a9f22883903d3b7fa52", + "@timestamp": "19:01:01", + "user_action": "user_browse_product" + }, + { + "traceID": "cfc90360b2af9906c1d26f63946cf3f2", + "@timestamp": "19:00:35", + "user_action": "user_browse_product" + }, + { + "traceID": "49dc9e79d76d07111558e64c191f4f9a", + "@timestamp": "18:57:56", + "user_action": "user_browse_product" + }, + { + "traceID": "67e333913a3f335b0cc2abd3439c77b2", + "@timestamp": "18:57:35", + "user_action": "user_browse_product" + }, + { + "traceID": "2058f8ce992fca41a8cb5c45221ab713", + "@timestamp": "18:56:25", + "user_action": "user_browse_product" + }, + { + "traceID": "a02e962f8e715a020a910a1af0615b13", + "@timestamp": "18:56:14", + "user_action": "user_browse_product" + }, + { + "traceID": "2a1744cea2fb056e14ac3e437ec24b5c", + "@timestamp": "18:56:13", + "user_action": "user_browse_product" + }, + { + "traceID": "55f18621f49c224748701a6be2dc5ad5", + "@timestamp": "18:55:49", + "user_action": "user_add_to_cart" + }, + { + "traceID": "8b5c15d35b248bba4911af850cc35953", + "@timestamp": "18:53:25", + "user_action": "user_browse_product" + }, + { + "traceID": "229ce5111e7677de8209bd20e6196bdf", + "@timestamp": "18:53:18", + "user_action": "user_browse_product" + }, + { + "traceID": "9995313407fd55c0ee6713019ed2ad24", + "@timestamp": "18:53:01", + "user_action": "user_browse_product" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 18:54:02 and 19:01:23 UTC, 5 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "639a3a40b1ba3ac0393cc75916c2fee1", + "@timestamp": "19:01:23", + "user_action": "user_get_recommendations" + }, + { + "traceID": "9ad42b010355b5689ab6ddf0e15eb394", + "@timestamp": "18:55:49", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ef962c94e4baef8f0fb867bbd2ac0e65", + "@timestamp": "18:55:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c4650d01c81c76b4ea6157dce1f31405", + "@timestamp": "18:54:36", + "user_action": "user_get_recommendations" + }, + { + "traceID": "c20c9698ecd0082c82521a014ea3b950", + "@timestamp": "18:54:02", + "user_action": "user_get_recommendations" + } + ] + } + ] + } +} diff --git a/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d4-d3dep-paymentunreachable-on-01-hard_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/environment/Dockerfile b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/environment/docker-compose.yaml b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/check_prediction.py b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/solve.py b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/solve.sh b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/check_prediction.py b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/expected.json b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/test.sh b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d4-d3dep-productcatalogfailure-on-11-easy_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubric.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.py b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.sh b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/expected.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6599eb5ef881e256c73baeda1c7a59c8ffa99a93 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,49 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-23T18:58:20.036794+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + }, + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + }, + { + "event_id": "d6-big-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T17:50:09.830911+00:00" + }, + { + "event_id": "d6-big-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:20:18.481618+00:00" + }, + { + "event_id": "d6-big-paymentFailure-100%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:50:26.427575+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/test.sh b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-00-hard_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/environment/Dockerfile b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/environment/docker-compose.yaml b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/check_prediction.py b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/solve.py b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/solve.sh b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/check_prediction.py b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/expected.json b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/test.sh b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-03-easy_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/environment/Dockerfile b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/rubric.json b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/rubric.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/solve.py b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/solve.sh b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/expected.json b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..4123247ec958815540230e27fa44b8df5a0cefc3 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-23T18:58:20.036794+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/test.sh b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-cartfailure-on-04-medium_ttd480m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/environment/Dockerfile b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/rubric.json b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/rubric.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/solve.py b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/solve.sh b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/expected.json b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6ff9833eaa4510f5b4433a0b445cf0ee1b46a126 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/test.sh b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-10-03-easy_ttd15m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubric.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/solve.py b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/solve.sh b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/expected.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..07a753e8c12f2c3e8707da671b4defc7867a9dc1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + }, + { + "event_id": "d5-d4dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-23T18:58:20.036794+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/test.sh b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-00-hard_ttd480m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/environment/Dockerfile b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubric.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubric.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/solve.py b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/solve.sh b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/expected.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5518a05b3745f3ed78390b6081aabf3e65914fd4 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + }, + { + "event_id": "d5-d4dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-23T18:58:20.036794+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/test.sh b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd15m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..07a753e8c12f2c3e8707da671b4defc7867a9dc1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,24 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + }, + { + "event_id": "d5-d4dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-23T18:58:20.036794+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-03-medium_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/environment/Dockerfile b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/solve.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/solve.sh b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/expected.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/test.sh b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_control_post60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/environment/Dockerfile b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubric.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubric.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/solve.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/solve.sh b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/expected.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5a4660e7d409e8825184e5ea158cdfe467095d9e --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/expected.json @@ -0,0 +1,14 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/test.sh b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd480m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/environment/Dockerfile b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubric.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubric.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/solve.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/solve.sh b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/expected.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5a4660e7d409e8825184e5ea158cdfe467095d9e --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/expected.json @@ -0,0 +1,14 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/test.sh b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentfailure-50-04-easy_ttd60m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/environment/Dockerfile b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubric.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubric.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/solve.py b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/solve.sh b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/expected.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..7d55e86eda4bbba3c6fa1065f65630db0f3282f4 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/test.sh b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/environment/Dockerfile b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubric.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubric.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/solve.py b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/solve.sh b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/expected.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..7d55e86eda4bbba3c6fa1065f65630db0f3282f4 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/test.sh b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-02-medium_ttd480m_range30m_off+60m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/environment/Dockerfile b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubric.json b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubric.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/solve.py b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/solve.sh b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/expected.json b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..7d55e86eda4bbba3c6fa1065f65630db0f3282f4 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/test.sh b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-03-easy_ttd480m_period_same-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/environment/Dockerfile b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubric.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubric.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-ic2-adFailure-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/solve.py b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/solve.sh b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/expected.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..3fb78ba5b03ddc54f8b3e8d4e277a3a8ba80cbd0 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/expected.json @@ -0,0 +1,34 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + }, + { + "event_id": "d5-ic2-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-23T14:26:55.696106+00:00" + }, + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + }, + { + "event_id": "d5-d4dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-23T18:58:20.036794+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-ic2-adFailure-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/test.sh b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_period_same-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/environment/Dockerfile b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubric.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-ic2-adFailure-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/solve.py b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/solve.sh b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/check_prediction.py b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/expected.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..3fb78ba5b03ddc54f8b3e8d4e277a3a8ba80cbd0 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/expected.json @@ -0,0 +1,34 @@ +{ + "events": [ + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + }, + { + "event_id": "d5-ic2-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-23T14:26:55.696106+00:00" + }, + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + }, + { + "event_id": "d5-d4dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-23T18:58:20.036794+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-ic2-adFailure-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/test.sh b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-d4dep-paymentunreachable-on-univ00-universal_ttd480m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/environment/Dockerfile b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/environment/docker-compose.yaml b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/check_prediction.py b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/rubric.json b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/solve.py b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/solve.sh b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/check_prediction.py b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/expected.json b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9633d81bd4b625febd7cf72c638a9b323c04295b --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/test.sh b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-01-hard_ttd15m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/environment/Dockerfile b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/environment/docker-compose.yaml b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/check_prediction.py b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/solve.py b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/solve.sh b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/check_prediction.py b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/expected.json b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/test.sh b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_control_post60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9633d81bd4b625febd7cf72c638a9b323c04295b --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-02-medium_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9633d81bd4b625febd7cf72c638a9b323c04295b --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-03-easy_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/environment/Dockerfile b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/environment/docker-compose.yaml b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/check_prediction.py b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubric.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-ic2-adFailure-on.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/solve.py b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/solve.sh b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/check_prediction.py b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/expected.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c9b38856c3d471a4e7503cdf1eb7d7bfbebc9019 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/expected.json @@ -0,0 +1,34 @@ +{ + "events": [ + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + }, + { + "event_id": "d5-ic2-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-23T14:26:55.696106+00:00" + }, + { + "event_id": "d5-d4dep-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-23T18:58:20.036794+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:28:43.282555+00:00" + }, + { + "event_id": "d5-d4dep-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-23T20:58:49.396441+00:00" + }, + { + "event_id": "d5-d4dep-paymentUnreachable-on", + "root_cause": "paymentUnreachable", + "event_time": "2026-04-23T21:28:57.350963+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-cartFailure-on.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..1bf02e1a5481a141d3b4279e2e82d4d4f7411092 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-cartFailure-on.json @@ -0,0 +1,417 @@ +{ + "incident_time": "2026-04-23T18:58:20.036794+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "SocketException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"SocketException\"}[2m])", + "description": "Rate of SocketExceptions in the cart service. Failed TCP connection attempts to the non-existent badhost:1234 generate a flood of SocketExceptions (1.6/s → 14.5/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline fluctuates around 1.55-1.77. At 18:59 the value is 1.8, still within noise. At 19:00 it jumps to 2.08, clearly breaking above the baseline range, and continues climbing steeply thereafter. This is the first unambiguous departure from the baseline pattern." + } + ] + }, + { + "metric_family": "dotnet_exceptions", + "signal_layer": "root_cause", + "defining_labels": { + "error_type": "TaskCanceledException", + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_exceptions_total{service_name=\"cart\",error_type=\"TaskCanceledException\"}[2m])", + "description": "Rate of TaskCanceledExceptions in the cart service. Long-blocking connection attempts cause pending async tasks to be cancelled (0.2/s → 1.4/s).", + "onset_utc": "2026-04-23 19:00:00 UTC", + "onset_offset_seconds": 99, + "onset_reasoning": "Pre-incident baseline is roughly 0.17–0.23. At 19:00 the value jumps to 0.283, clearly above the baseline range, and continues rising steeply thereafter. This is the first timestamp after the incident where the metric begins its sustained climb." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds_sum) / rate(rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_method": "EmptyCart", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m]) / rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\", rpc_method=\"EmptyCart\"}[5m])", + "description": "Average EmptyCart RPC duration from checkout spiked from ~4ms to 130,000–1,800,000ms — ConnectionMultiplexer.Connect retries with exponential backoff against the unreachable badhost:1234 before eventually throwing", + "onset_utc": "2026-04-23 18:54:00 UTC", + "onset_offset_seconds": -260, + "onset_reasoning": "The pre-incident baseline is roughly 3.5-5.0ms (with one brief spike to 6.11 at 18:46). At 18:54 the value jumps to 7.13, clearly above baseline, and sustains elevated values (8.23, 7.36, 7.05) through 18:57. This spike precedes the recorded incident time by ~4 minutes, consistent with the 5-minute rate window capturing the underlying change. After the incident time the metric drops and goes null, so the spike onset is at 18:54." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "fraud-detection", + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\",service_name=\"fraud-detection\"}", + "description": "Bytes consumed by fraud-detection from the Kafka 'orders' topic dropped ~70% for the same reason — fewer order messages are produced per unit time while PlaceOrder RPCs are blocked on the hung EmptyCart call.", + "onset_utc": "2026-04-23 18:56:00 UTC", + "onset_offset_seconds": -140, + "onset_reasoning": "Pre-incident, the metric oscillates with frequent non-zero values (averaging ~8-10) interspersed with occasional zeros. The last non-trivial value before the signal collapses is 6.37 at 18:56. After that, the metric enters a sustained zero/near-zero pattern. Post-incident, values only appear every other minute at ~4-6 (roughly half the pre-incident average), consistent with a collapsed state rather than recovery. The onset at 18:56 aligns closely with the incident time of 18:58." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "off" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\", feature_flag_result_variant=\"off\"}[5m])", + "description": "flagd impression count for cartFailure evaluating to 'off' — dropped from ~0.02/s to zero when the flag was flipped on, as EmptyCart calls now resolve to the 'on' variant instead", + "onset_utc": "2026-04-23 18:57:00 UTC", + "onset_offset_seconds": -80, + "onset_reasoning": "The pre-incident signal oscillates around 0.01-0.03 through 18:57. At 18:58 it drops sharply to 0.004 and hits 0 at 18:59, never recovering. The last timestamp with a normal pre-incident value is 18:57 (0.0167), making it the onset — the last active reading before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 18:58:40.731 and 19:08:10.476 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T18:58:40.731Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 380 24 15003 - \"-\" \"python-requests/2.32.5\" \"13bbac02-02a2-9812-a8cc-15b40bc5f00b\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:41144 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "nNe1u50Br_RFnSwRooF9", + "@timestamp": "18:58:40.731" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "f9e2u50Br_RFnSwRP4N3", + "@timestamp": "18:59:21.297" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Cte2u50Br_RFnSwR3oXw", + "@timestamp": "19:00:02.120" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "xte4u50Br_RFnSwRoYkD", + "@timestamp": "19:01:57.414" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "B9e4u50Br_RFnSwR64tC", + "@timestamp": "19:02:15.865" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "INe5u50Br_RFnSwRTYwI", + "@timestamp": "19:02:40.893" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Yde5u50Br_RFnSwRuo15", + "@timestamp": "19:03:08.935" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "rde6u50Br_RFnSwRHI4o", + "@timestamp": "19:03:33.920" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hte7u50Br_RFnSwRtpNm", + "@timestamp": "19:05:18.796" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "u9e7u50Br_RFnSwR2JOn", + "@timestamp": "19:05:27.955" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "dte8u50Br_RFnSwRFJQq", + "@timestamp": "19:05:43.129" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5te9u50Br_RFnSwRbJgb", + "@timestamp": "19:07:10.684" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Mte9u50Br_RFnSwR5Jo1", + "@timestamp": "19:07:42.310" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "bte-u50Br_RFnSwRUpuT", + "@timestamp": "19:08:10.476" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC the cart service emitted 4 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore. Each carries the traceId of one of the failing checkout requests in the POST /api/checkout 504 cluster, directly linking the downstream timeouts to this root-cause signal.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Sde3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "L9e5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.786" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "i9e7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.788" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "M9e9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 19:00:50.772 and 19:06:55.479 UTC (4 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "1dd3a2182754a0215a74f9d4018e716a", + "spanId": "7130f2a0ab074897", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "Ste3u50Br_RFnSwRbobW", + "@timestamp": "19:00:50.772" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNe5u50Br_RFnSwRV4wt", + "@timestamp": "19:02:55.787" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNe7u50Br_RFnSwRGJF0", + "@timestamp": "19:04:53.789" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "NNe9u50Br_RFnSwRAJfL", + "@timestamp": "19:06:55.479" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 18:58:40 and 19:08:06 UTC (20 s to ~9.8 min after cartFailure was flipped on at 18:58:20 UTC), 14 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 130–1141 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 130 s and 1141 s across the 14 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "e62cfbf4a4498bec490d05a487f663d2", + "@timestamp": "19:08:06", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1140.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "48b4938be6410fc9e0a1ae01c7d1b1da", + "@timestamp": "19:07:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "1059.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "af66ed82e652a52a6ae460147e87b146", + "@timestamp": "19:07:10", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "969.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "025111871e3d82ea201c57c82b3dcd4e", + "@timestamp": "19:05:43", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "934.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "170b2d19b53fbde35f06cbf4b0cf464a", + "@timestamp": "19:05:27", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "837.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "429444bb6856ea1c30c77a0902ed0272", + "@timestamp": "19:05:18", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "724.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a9902e3b7c9e18c1c44d45b49485d55e", + "@timestamp": "19:03:33", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "706.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "0d3df581377c11585792b76bd04aef09", + "@timestamp": "19:03:08", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "605.5", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "92ce296778b9ed5031d814c9b4cff1cb", + "@timestamp": "19:02:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "503.1", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "3084185fb85cc0e2ca8dfa1a0b1e54b3", + "@timestamp": "19:02:15", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "400.9", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "9e5f6f6de1dbb277b49e2bb12ad3a49e", + "@timestamp": "19:01:57", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "298.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "a54b288e878a7475b282e3212888cca9", + "@timestamp": "19:00:02", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "291.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "5dbf27e0b9abdf387b7c5246815d2c0b", + "@timestamp": "18:59:21", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "214.4", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "1dd3a2182754a0215a74f9d4018e716a", + "@timestamp": "18:58:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "130.0", + "frontend_proxy_http_status": "504" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-10%.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..ff1d3c0d5f67eee2c11658427ebe7e19acac0c12 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-10%.json @@ -0,0 +1,216 @@ +{ + "incident_time": "2026-04-23T20:28:43.282555+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. Spiked from 0 when the paymentFailure flag began causing 10% of charge requests to throw 'Payment request failed' errors.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it jumps to ~0.00417, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the error-rate spike for the payment service Charge span." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error duration counter for payment Charge RPC. Spiked from 0, tracking the count of error-status span durations generated by the paymentFailure flag.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to ~0.00417, which is the initial spike above the zero baseline following the incident at 20:28:43." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"2\",rpc_method=\"Charge\",rpc_service=\"oteldemo.PaymentService\"}[5m])", + "description": "Checkout's outgoing Charge gRPC calls to the payment service returning UNKNOWN (code 2). The payment service throws Error('Payment request failed. Invalid token.') which maps to gRPC UNKNOWN on the client side.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. After the incident at 20:28:43, the first non-zero value appears at 20:31:00 (0.00416667), marking the onset of the spike in successful Charge RPC calls from checkout to PaymentService." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500. The paymentFailure flag causes charge.js to throw an error 10% of the time, which propagates through checkout as gRPC INTERNAL and is returned to the frontend as HTTP 500.", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is flat at 0 from 20:08 through 20:30. At 20:31 it first rises to 0.00416667, which is the first non-zero value after the incident time (20:28:43). This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "rpc_service": "oteldemo.CheckoutService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"13\",rpc_method=\"PlaceOrder\",rpc_service=\"oteldemo.CheckoutService\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13). The payment error propagates through checkout's chargeCard (main.go:552) causing PlaceOrder to return codes.Internal (main.go:335).", + "onset_utc": "2026-04-23 20:31:00 UTC", + "onset_offset_seconds": 136, + "onset_reasoning": "The metric is consistently 0 before the incident. The first non-zero value after the incident time (20:28:43) appears at 20:31 (0.00416667), indicating the start of gRPC status_code=13 errors on CheckoutService PlaceOrder." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "zdgIvJ0Br_RFnSwRa3in", + "@timestamp": "20:29:20.706" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ttgKvJ0Br_RFnSwRSH9B", + "@timestamp": "20:31:22.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "DtgevJ0Br_RFnSwRiMmk", + "@timestamp": "20:53:30.268" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–34ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "RdgIvJ0Br_RFnSwRf3k8", + "@timestamp": "20:29:20.741" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "MNgKvJ0Br_RFnSwRUYAs", + "@timestamp": "20:31:22.895" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "c9gevJ0Br_RFnSwRnMl4", + "@timestamp": "20:53:30.300" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:29:20 and 20:53:30 UTC, 3 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "0f13fb5e7d362c1d8eb8550e6cd7e779", + "@timestamp": "20:29:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5555415e23fee1960b5597d60869cbc6", + "@timestamp": "20:31:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "16a8fb39ce815b299d7948da46f5ee21", + "@timestamp": "20:53:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-50%.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..911ae60cfaf9831dacd3cb53e30a1cc0ea1ac19c --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentFailure-50%.json @@ -0,0 +1,313 @@ +{ + "incident_time": "2026-04-23T20:58:49.396441+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Cumulative error-span duration rate for payment Charge increased ~2.67x — more error spans means more total milliseconds accumulated in the duration histogram.", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline is essentially zero with only sporadic low-magnitude blips (max ~0.004). After the incident at 20:58:49, the value at 20:59 and 21:00 is 0, then at 21:01 it jumps to 0.0281, nearly 7x the largest pre-incident blip, and remains elevated with sustained high values (0.036, 0.040, etc.). This is the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(traces_span_metrics_duration_milliseconds_count{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Error-span duration observation count for payment Charge increased ~2.25x, tracking the same doubling in error span volume seen in calls_total.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level errors around 0.004 (roughly 1 error per 5-min window). After the incident at 20:59, the value at 21:01 is 0.004 which is still baseline. At 21:02 it jumps to 0.0125, which is 3x the baseline, and continues rising to 0.033 — a clear sustained spike well above the prior intermittent noise." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{status_code=\"STATUS_CODE_ERROR\", service_name=\"payment\", span_name=\"oteldemo.PaymentService/Charge\"}[5m])", + "description": "Span-derived error call rate for payment service's Charge RPC doubled (~2.25x) because the paymentFailure flag causes 50% of charge requests to throw an error, generating STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-23 21:02:00 UTC", + "onset_offset_seconds": 190, + "onset_reasoning": "Pre-incident baseline shows occasional blips of ~0.004 with zeros between. After the incident at 20:58:49, the value at 21:01 is still at baseline (~0.004), but at 21:02 it jumps to 0.0125 (~3x baseline) and continues to rise to sustained elevated levels (0.017-0.033), clearly above the pre-incident pattern. This marks the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "rpc_service": "oteldemo.PaymentService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_service=\"oteldemo.PaymentService\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout's outbound gRPC calls to PaymentService/Charge returning UNKNOWN (code 2) errors increased ~2.7x due to the payment service throwing errors on 50% of charges", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level activity (~0.004). After the incident at 20:59, the value at 21:00 is 0, then at 21:01 it jumps to 0.00833326 (2x baseline) and continues rising to sustained higher levels (0.0167-0.033), indicating the spike onset at 21:01." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend POST /api/checkout HTTP 500 responses spiked ~4x as payment failures cascade through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level 500s (~0.004) with gaps of zero. After the incident at 20:58:49, the value at 21:01 jumps to 0.00833319 and then escalates to 0.0167-0.0333, roughly 4-8x the pre-incident sporadic level. 21:01 is the first post-incident timestamp where the rate clearly rises above the prior baseline and sustains elevated values." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Rate of checkout PlaceOrder gRPC calls failing with INTERNAL (code 13) spiked ~4x because payment charge failures propagate through the checkout service as gRPC Internal errors", + "onset_utc": "2026-04-23 21:01:00 UTC", + "onset_offset_seconds": 130, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level noise (~0.004) with frequent zeros. After the incident at 20:58:49, the metric drops to 0 at 20:59-21:00, then at 21:01 jumps to 0.00833326 and continues rising to sustained higher levels (0.0167-0.0333), well above the pre-incident baseline. 21:01 is the first post-incident timestamp where the sustained spike begins." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "pNgkvJ0Br_RFnSwRdt6x", + "@timestamp": "20:59:58.578" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "9NgkvJ0Br_RFnSwRit7Z", + "@timestamp": "21:00:04.637" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ztgkvJ0Br_RFnSwR9OAD", + "@timestamp": "21:00:31.080" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "FdglvJ0Br_RFnSwRjOOO", + "@timestamp": "21:01:09.779" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "1NgovJ0Br_RFnSwRte5h", + "@timestamp": "21:04:37.390" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BNgpvJ0Br_RFnSwR8vMW", + "@timestamp": "21:05:58.744" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "x9grvJ0Br_RFnSwRTvdV", + "@timestamp": "21:07:27.840" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "6NgrvJ0Br_RFnSwRq_jN", + "@timestamp": "21:07:51.406" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "BdgsvJ0Br_RFnSwRRPtq", + "@timestamp": "21:08:30.708" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 25–60ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7tgkvJ0Br_RFnSwRiN7P", + "@timestamp": "20:59:58.622" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "hdgkvJ0Br_RFnSwRoN9v", + "@timestamp": "21:00:04.689" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9glvJ0Br_RFnSwRBuE3", + "@timestamp": "21:00:31.140" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "ONglvJ0Br_RFnSwRnuTI", + "@timestamp": "21:01:09.835" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "htgovJ0Br_RFnSwRyO-r", + "@timestamp": "21:04:37.430" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "mdgqvJ0Br_RFnSwRCfNv", + "@timestamp": "21:05:58.775" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "JNgrvJ0Br_RFnSwRYfjV", + "@timestamp": "21:07:27.866" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "gtgrvJ0Br_RFnSwRv_nK", + "@timestamp": "21:07:51.452" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "jNgsvJ0Br_RFnSwRWPtX", + "@timestamp": "21:08:30.745" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 20:59:58 and 21:08:30 UTC, 9 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "81afda347c12b3c3902be56e48f6600d", + "@timestamp": "20:59:58", + "user_action": "user_checkout_single" + }, + { + "traceID": "fa54b76a44cf88422637d903b4a9792d", + "@timestamp": "21:00:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "314062c3f1393d703b178aceff414eb2", + "@timestamp": "21:00:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "66b7489ff31e0a9a48da315a5018d524", + "@timestamp": "21:01:09", + "user_action": "user_checkout_multi" + }, + { + "traceID": "261b56713803f6676857e04ffa12fd88", + "@timestamp": "21:04:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "0e3b38384733f2e4591f783acc188a95", + "@timestamp": "21:05:58", + "user_action": "user_checkout_multi" + }, + { + "traceID": "99f37a257d110dd7899771d961e2b3f8", + "@timestamp": "21:07:27", + "user_action": "user_checkout_single" + }, + { + "traceID": "e0df7e8df2f4a07d9b51aa7107273786", + "@timestamp": "21:07:51", + "user_action": "user_checkout_multi" + }, + { + "traceID": "7897367afe7cf7ea7643f6610565392a", + "@timestamp": "21:08:30", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json new file mode 100644 index 0000000000000000000000000000000000000000..5e1932579324e47cce0506117eac4a3d5f5b9659 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-d4dep-paymentUnreachable-on.json @@ -0,0 +1,263 @@ +{ + "incident_time": "2026-04-23T21:28:57.350963+00:00", + "feature_flag": "paymentUnreachable", + "description": "A feature flag read in the checkout service's `chargeCard` rebuilt the payment gRPC client against the unresolvable host `badAddress:50051`; the subsequent `paymentService.Charge()` failed DNS lookup and returned gRPC `Unavailable`, `PlaceOrder` returned `codes.Internal`, and the frontend surfaced HTTP 500s on `POST /api/checkout`.", + "mechanism": "The flag is read in the checkout service's `chargeCard` function at [`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546). When enabled, it replaces the payment service client with one pointing to `badAddress:50051`, causing a DNS lookup failure. The checkout service creates a new gRPC client to this bad address at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549), so the subsequent `paymentService.Charge()` call at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552) fails with a gRPC `Unavailable` status.\n\nThe call chain is:\n\n1. **[`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)** — `chargeCard` checks the `paymentUnreachable` feature flag.\n2. **[`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549)** — If enabled, creates a new gRPC client pointing to `badAddress:50051`.\n3. **[`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552)** — `paymentService.Charge()` fails because DNS cannot resolve `badAddress`.\n4. **[`main.go#L333-335`](../../opentelemetry-demo/src/checkout/main.go#L333-L335)** — `PlaceOrder` calls `cs.chargeCard()` and returns `codes.Internal` on failure.\n5. **Frontend** — Surfaces the error as an HTTP 500 when the user clicks \"Place Order\".", + "symptoms": { + "metrics": [ + { + "metric_family": "go_goroutine", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "go_goroutine_count{service_name=\"checkout\"}", + "description": "Checkout service goroutine count rose from ~856 to 964 after the incident. Each failed gRPC dial to badAddress:50051 spawns goroutines for DNS resolution and connection attempts that accumulate because the connections never succeed.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident baseline is ~855-867, slowly drifting down. At 21:31 the value jumps to 868, breaking above the prior baseline range, and continues climbing steadily to 936 by 21:48. This is the first clear upward departure after the incident time." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"14\"}[5m])", + "description": "gRPC client calls from checkout to PaymentService/Charge returning UNAVAILABLE (status 14). The paymentUnreachable flag redirects the gRPC dial to badAddress:50051, causing DNS resolution failure and gRPC UNAVAILABLE errors on every charge attempt.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. The first non-zero value appears at 21:31:00 (0.0125), roughly 2 minutes after the incident time, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Payment service PaymentService/Charge UNSET calls collapsed to zero. The payment service is never reached because the checkout service dials badAddress:50051 instead of the real payment service, so no spans are generated on the payment side.", + "onset_utc": "2026-04-23 21:31:00 UTC", + "onset_offset_seconds": 122, + "onset_reasoning": "Pre-incident, the metric shows periodic activity with values oscillating between ~0.004-0.017, interspersed with occasional zeros. After the incident at 21:28:57, the last non-zero reading is at 21:32:00 (0.00416667). At 21:33:00 the signal drops to zero and never recovers. The onset of collapse is 21:31:00, the last timestamp where the diminished but still-active pattern continues before the final death at 21:33:00." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentUnreachable", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentUnreachable\",feature_flag_result_variant=\"on\"}[5m])", + "description": "Flagd impressions for the paymentUnreachable feature flag evaluating to the 'on' variant. Confirms the flag was activated and being evaluated by the checkout service via flagd.", + "onset_utc": "2026-04-23 21:30:00 UTC", + "onset_offset_seconds": 62, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident baseline. At 21:30 UTC (about 1 minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"0\"}[5m])", + "description": "Successful gRPC client calls from checkout to PaymentService/Charge (status OK=0). Dropped to zero because all charge attempts now fail with UNAVAILABLE due to the bad gRPC endpoint.", + "onset_utc": "2026-04-23 21:32:00 UTC", + "onset_offset_seconds": 182, + "onset_reasoning": "The pre-incident pattern shows periodic activity oscillating around 0.0125-0.0167 with occasional brief dips to zero that recover. After the incident at 21:28:57, the signal continues at a reduced level (~0.004) until 21:32, then drops to zero permanently and never recovers. 21:32 is the last non-trivial value before the permanent collapse, aligning with the incident timing." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 POST /api/checkout requests returned HTTP 500 with a 21-byte error response body. The DNS lookup for badAddress fails on the checkout service, so the payment service is never contacted.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard redirects payment gRPC calls to badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549), causing a DNS lookup failure. The checkout service wraps this as \"could not charge the card\" (main.go:555-556) and returns gRPC Internal (main.go:334-335), which the frontend proxies as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T21:29:24.247Z] \"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 388 21 51 50 \"-\" \"python-requests/2.32.5\" \"affffe95-29c8-947f-a716-816f80c95937\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:33986 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "wtk_vJ0Br_RFnSwRZTco", + "@timestamp": "21:29:24.247" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "Z9k_vJ0Br_RFnSwRuzlp", + "@timestamp": "21:29:45.871" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "r9lAvJ0Br_RFnSwRDTrF", + "@timestamp": "21:30:06.957" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KtlBvJ0Br_RFnSwRMD4H", + "@timestamp": "21:31:21.291" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "5dlDvJ0Br_RFnSwRLkNM", + "@timestamp": "21:33:31.911" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "K9lFvJ0Br_RFnSwRCEnF", + "@timestamp": "21:35:33.752" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "G9lFvJ0Br_RFnSwR3EyG", + "@timestamp": "21:36:27.668" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "GtlGvJ0Br_RFnSwRYU7f", + "@timestamp": "21:37:01.988" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "N9lGvJ0Br_RFnSwR9lDZ", + "@timestamp": "21:37:39.828" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "oNlHvJ0Br_RFnSwRClCq", + "@timestamp": "21:37:45.478" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "KNlHvJ0Br_RFnSwRbFJl", + "@timestamp": "21:38:10.397" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error — the user remains on the cart page and never reaches the order confirmation. Unlike cartFailure (which hangs for ~15 seconds), the failure is fast (~50 ms) because the DNS lookup for badAddress fails immediately. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentUnreachable is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which internally creates a gRPC client to `badAddress:50051` at [`main.go#L547-549`](../../opentelemetry-demo/src/checkout/main.go#L547-L549) and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333). With paymentUnreachable enabled, `chargeCard` ([`main.go#L546`](../../opentelemetry-demo/src/checkout/main.go#L546)) creates a new gRPC client pointing to `badAddress:50051` and calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). DNS cannot resolve `badAddress`, returning gRPC `Unavailable`. `chargeCard` wraps this as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` (`\"failed to charge card\"`) at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Unreachable Cascade", + "description": "Between 21:29:24 and 21:38:10 UTC, 11 traces show checkout failing to reach the payment service due to DNS resolution failure at badAddress:50051, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentUnreachable flag — checkout service's chargeCard creates a gRPC client pointing at badAddress:50051 instead of the real payment service (src/checkout/main.go:546-549). DNS lookup fails with 'server misbehaving', returning gRPC Unavailable. The payment service never receives the request.", + "call_chain": "checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "checkout:PlaceOrder span log: feature_flag.key=paymentUnreachable, feature_flag.result.variant=on", + "checkout:PaymentService/Charge span: otel.status_code=ERROR, otel.status_description=\"dns: A record lookup error: lookup badAddress on 127.0.0.11:53: server misbehaving\", rpc.grpc.status_code=Unavailable", + "payment service absent from trace processes — request never reaches the payment service" + ], + "trace_documents": [ + { + "traceID": "87a5d178155c812f534c71d7aa31c53f", + "@timestamp": "21:29:24", + "user_action": "user_checkout_multi" + }, + { + "traceID": "08a94094df044be0835373c967743871", + "@timestamp": "21:29:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "3ce21003d5118efd46efd036bf8d20c7", + "@timestamp": "21:30:02", + "user_action": "user_checkout_single" + }, + { + "traceID": "94042d8e2795463454e5ac078385fcc8", + "@timestamp": "21:31:21", + "user_action": "user_checkout_single" + }, + { + "traceID": "461fd9b652ed63844c0a8f683dd6a66e", + "@timestamp": "21:33:31", + "user_action": "user_checkout_multi" + }, + { + "traceID": "55d50329e3f18c705fddd407d0aab564", + "@timestamp": "21:35:33", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ea07cc5baa99070bcdeab0ff266dad6f", + "@timestamp": "21:36:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "47a00dd7e4a88fb018e1fe486b73cbf4", + "@timestamp": "21:37:01", + "user_action": "user_checkout_multi" + }, + { + "traceID": "5874e0f72079197a32c2dbff63445ffe", + "@timestamp": "21:37:39", + "user_action": "user_checkout_multi" + }, + { + "traceID": "1ffbb484af3476fdd5840ed1301f6d2e", + "@timestamp": "21:37:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "aeba033301a58ac460c1fdbe8b4e8b1c", + "@timestamp": "21:38:10", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-ic2-adFailure-on.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/test.sh b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-imageslowload-on-univ00-universal_ttd480m_range30m_off+60m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/environment/Dockerfile b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/environment/docker-compose.yaml b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/check_prediction.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/rubric.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/solve.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/solve.sh b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/check_prediction.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/expected.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9633d81bd4b625febd7cf72c638a9b323c04295b --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/test.sh b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-02-medium_ttd60m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/environment/Dockerfile b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/environment/docker-compose.yaml b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/check_prediction.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/solve.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/solve.sh b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/check_prediction.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/expected.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/test.sh b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/environment/Dockerfile b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/environment/docker-compose.yaml b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/check_prediction.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/rubric.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/rubric.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/solve.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/solve.sh b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/check_prediction.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/expected.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9633d81bd4b625febd7cf72c638a9b323c04295b --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/test.sh b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-03-easy_ttd480m_period_same-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/environment/Dockerfile b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/check_prediction.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubric.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-adFailure-on.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.sh b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/check_prediction.py b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/expected.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..15a8da2c601665ebd579eeca81f47ee081db1173 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/expected.json @@ -0,0 +1,14 @@ +{ + "events": [ + { + "event_id": "d5-ic2-adFailure-on", + "root_cause": "adFailure", + "event_time": "2026-04-23T14:26:55.696106+00:00" + }, + { + "event_id": "d5-ic2-imageSlowLoad-on", + "root_cause": "imageSlowLoad", + "event_time": "2026-04-23T14:52:01.764552+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-adFailure-on.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-adFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a2b97bf9bee2c579109c73ab046019c8d4e53761 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-adFailure-on.json @@ -0,0 +1,232 @@ +{ + "incident_time": "2026-04-23T14:26:55.696106+00:00", + "feature_flag": "adFailure", + "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.", + "mechanism": "The flag is read in [`AdService.java#L205`](../../opentelemetry-demo/src/ad/src/main/java/oteldemo/AdService.java#L205). When the flag evaluates to `true` (10% of requests), the service throws a `StatusRuntimeException` with gRPC status `UNAVAILABLE`, causing the `GetAds` RPC to fail.\n\nThe error propagates through the following call chain:\n\n1. **Ad component** (`Ad.tsx`) calls the `useAd()` hook\n2. **Ad provider** (`Ad.provider.tsx`) uses React Query to call `ApiGateway.listAds()`\n3. **API gateway** (`Api.gateway.ts`) makes an HTTP GET to `/api/data`\n4. **API route** (`data.ts`) calls `AdGateway.listAds()` via gRPC\n5. **gRPC gateway** (`Ad.gateway.ts`) calls `client.getAds()` — this is where the `UNAVAILABLE` error arrives\n\nError handling at each layer:\n\n- **gRPC gateway** — rejects the promise with the gRPC error\n- **API route** — the `InstrumentationMiddleware` catches the error, records an exception on the span, sets span status to `ERROR`, and returns HTTP 500\n- **React Query** — the query fails, but defaults to `adList = []` (empty array)\n- **Ad component** — handles the empty array gracefully with a `|| { text: '', redirectUrl: '' }` fallback\n\nWhat the user sees is silent degradation — the ad section renders as an empty/blank area (no ad text, no link). The page continues to work normally with no error message shown to the user. The ads just disappear.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "gRPC server-side count of AdService GetAds calls returning UNAVAILABLE (status 14). This new time series appeared only after the adFailure flag was enabled, directly counting the StatusRuntimeException(Status.UNAVAILABLE) throws at AdService.java:206.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type, meaning the time series did not exist before the incident. The series first appears at 14:32:00 UTC, approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance represents the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors) on the AdService." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_duration_milliseconds_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total server-side duration (ms) of AdService GetAds calls failing with UNAVAILABLE. New series appearing after the flag was enabled, accumulating latency for the ~10% of requests that hit the probabilistic failure path.", + "onset_utc": "2026-04-23 14:37:00 UTC", + "onset_offset_seconds": 604, + "onset_reasoning": "The metric is flat at 18.9622 from 14:32–14:36 (pre-incident baseline). At 14:37 it jumps to 20.7945, indicating the first appearance of new RPC error duration accumulation. This is the first timestamp after the incident time (14:26:55) where the value clearly rises above baseline." + } + ] + }, + { + "metric_family": "rpc_server_response_size_bytes", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "14", + "rpc_method": "GetAds", + "rpc_service": "oteldemo.AdService", + "service_name": "ad" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_count{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Count of gRPC response messages from ad service GetAds calls failing with UNAVAILABLE. New series tracking the error responses sent back to the frontend via responseObserver.onError().", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "The metric type is 'created', meaning the time series did not exist before the incident. The first data point appears at 14:32:00 UTC with value 1, which is approximately 5 minutes after the incident time of 14:26:55 UTC. This first appearance of the series marks the onset of the new error condition (rpc_grpc_status_code=14 indicating UNAVAILABLE errors)." + }, + { + "type": "created (fixed after human verification)", + "query": "rpc_server_response_size_bytes_sum{service_name=\"ad\",rpc_service=\"oteldemo.AdService\",rpc_method=\"GetAds\",rpc_grpc_status_code=\"14\"}", + "description": "Total response bytes for ad service GetAds UNAVAILABLE errors. New series accumulating the (small) error response payload sizes for failed gRPC calls.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "This is a 'created' metric type. The time series first appears at 14:32:00 UTC with a value of 8, which is after the incident time of 14:26:55 UTC. Since the series did not exist before the incident and its first appearance at 14:32:00 represents the creation of this error-related metric (rpc_grpc_status_code=14 indicates UNAVAILABLE errors), this is the onset time." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "propagation", + "defining_labels": { + "status": "500", + "target": "/api/data" + }, + "variants": [ + { + "type": "spiked", + "query": "app_frontend_requests_total{status=\"500\",target=\"/api/data\"}", + "description": "Frontend application-level counter for GET /api/data returning HTTP 500. Rate spiked from 0 after the flag was enabled because the ad service gRPC UNAVAILABLE errors propagate through Ad.gateway.ts and the Next.js /api/data route handler as unhandled rejections, resulting in 500 responses.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is steady at 59. After the incident at 14:26:55, the value remains at 59 until 14:31. At 14:32 it rises to 60, marking the first clear departure from the baseline. The metric continues climbing to 61 by 14:37, confirming a sustained spike." + } + ] + }, + { + "metric_family": "http_client_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "http_method": "GET", + "http_status_code": "500", + "service_name": "load-generator" + }, + "variants": [ + { + "type": "spiked", + "query": "http_client_duration_milliseconds_count{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Load generator HTTP client count of GET requests receiving 500 responses. Rate spiked from 0 after the incident as the load generator's user_get_ads calls hit the ad service failure path and receive HTTP 500 from the frontend-proxy.", + "onset_utc": null, + "onset_offset_seconds": null, + "onset_reasoning": "The metric shows only a trivial drift from 570 to 571-572 over several minutes after the incident, which is normal counter noise (a cumulative count incrementing by 1-2 over 15 minutes). There is no clear spike — a genuine spike in an HTTP 500 count metric would show a sharp, significant increase. This minimal change does not constitute a meaningful onset." + }, + { + "type": "spiked", + "query": "http_client_duration_milliseconds_sum{service_name=\"load-generator\",http_method=\"GET\",http_status_code=\"500\"}", + "description": "Total client-side duration (ms) for load generator GET requests receiving 500 responses. Rate spiked from 0, tracking the round-trip time of failed requests.", + "onset_utc": "2026-04-23 14:32:00 UTC", + "onset_offset_seconds": 304, + "onset_reasoning": "Pre-incident baseline is flat at 8018. The first increase above baseline occurs at 14:32 (value jumps to 8046), approximately 5 minutes after the incident time." + } + ] + }, + { + "metric_family": "container_memory_usage_total_bytes", + "signal_layer": "meta", + "defining_labels": { + "container_name": "ad" + }, + "variants": [ + { + "type": "spiked", + "query": "container_memory_usage_total_bytes{container_name=\"ad\"}", + "description": "Ad container memory usage stepped up ~6.3 MB (from ~273 MB to ~279.5 MB) at incident onset, as the JVM loaded and JIT-compiled the exception-handling code path (StatusRuntimeException throw/catch, error span event creation, WARN logging) triggered by the adFailure flag.", + "onset_utc": "2026-04-23 14:31:00 UTC", + "onset_offset_seconds": 244, + "onset_reasoning": "Pre-incident baseline is ~273.2M bytes (stable ±0.15M). At 14:31 the value jumps to ~279.5M bytes (~6.3M increase, ~2.3%), establishing a new sustained plateau around 279.5M. The brief blip at 14:27 (273.4M) is within normal noise, but 14:31 marks the clear, sustained shift upward." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/data → 500", + "description": "Between 14:30:35 and 14:36:03 UTC, GET /api/data?contextKeys=travel returned 500 errors twice (2 failures out of 25 completed /api/data requests after the incident, ~8%, matching the 1/10 probabilistic failure rate). Both failing requests sampled the same category (travel). Each shares its traceId with an ad-service GetAds UNAVAILABLE WARN logged ~5-20 ms later.", + "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.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-23T14:30:35.940Z] \"GET /api/data?contextKeys=travel HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 22 21 \"-\" \"python-requests/2.32.5\" \"b81a8261-9783-9438-a5f2-34f3abf6533c\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend", + "event.name": "proxy.access", + "url.full": "http://frontend-proxy:8080/api/data?contextKeys=travel", + "url.path": "/api/data?contextKeys=travel", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "43f0b1a051dc9458" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "79K_up0Br_RFnSwR-aXw", + "@timestamp": "14:30:35.940" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PtLEup0Br_RFnSwR97qE", + "@timestamp": "14:36:03.139" + } + ] + }, + { + "name": "ad: GetAds Failed (WARN)", + "description": "Between 14:30:35 and 14:36:03 UTC, the ad service emitted 2 WARN logs reporting that GetAds failed with gRPC status UNAVAILABLE. Each WARN arrives ~5-20 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).", + "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.", + "source": "ad service (Java, oteldemo.AdService logger via OpenTelemetry Java agent)", + "representative_attributes": { + "body": "GetAds Failed with status Status{code=UNAVAILABLE, description=null, cause=null}", + "severity.text": "WARN", + "severity.number": "13", + "instrumentationScope.name": "oteldemo.AdService", + "resource.service.name": "ad", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "java", + "resource.telemetry.distro.name": "opentelemetry-java-instrumentation", + "traceId": "9f51b74430ba0c5f7f28f000f0a92631", + "spanId": "aeb3456df5f6d877" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-23", + "_id": "7dK_up0Br_RFnSwR-aUe", + "@timestamp": "14:30:35.959" + }, + { + "_index": "otel-logs-2026-04-23", + "_id": "PNLEup0Br_RFnSwR9rrJ", + "@timestamp": "14:36:03.144" + } + ] + } + ], + "frontend": [ + { + "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.", + "route": "GET /api/data", + "deterministic": false, + "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)).", + "source_file": "src/frontend/pages/api/data.ts", + "source_line": 15, + "calling_service": "frontend", + "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)).", + "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.", + "symptom_type": "visual_degradation" + } + ], + "traces": [ + { + "name": "GetAds UNAVAILABLE Cascade", + "description": "Between 14:30:35 and 14:36:03 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 ~5.5 minutes apart, consistent with the load generator's user_get_ads cadence multiplied by the ~1/10 probabilistic failure rate.", + "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.", + "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", + "smoking_gun": [ + "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", + "ad:oteldemo.AdService/GetAds span attributes app.ads.count=1 and app.ads.ad_request_type=TARGETED with app.ads.contextKeys=[travel], 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)", + "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", + "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(...))" + ], + "trace_documents": [ + { + "traceID": "9f51b74430ba0c5f7f28f000f0a92631", + "@timestamp": "14:30:35", + "user_action": "user_get_ads" + }, + { + "traceID": "4f56c8ab8e45e6961ac2aaffeb713c7b", + "@timestamp": "14:36:03", + "user_action": "user_get_ads" + } + ] + } + ] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json new file mode 100644 index 0000000000000000000000000000000000000000..8427a40fee9407a9af0cb99b40d2f1ea01a92584 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/rubrics/d5-ic2-imageSlowLoad-on.json @@ -0,0 +1,24 @@ +{ + "incident_time": "2026-04-23T14:52:01.764552+00:00", + "feature_flag": "imageSlowLoad", + "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/` response, so product thumbnails took seconds to render.", + "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/`, 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.", + "symptoms": { + "metrics": [], + "logs": [], + "frontend": [ + { + "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.", + "route": "GET /images/products/", + "deterministic": true, + "trigger_condition": "Every page load that renders a `ProductCard` component — homepage product grid (`/`), recommendations carousel on product detail (`/product/`), cart, and checkout pages.", + "source_file": "src/frontend/components/ProductCard/ProductCard.tsx", + "source_line": 37, + "calling_service": "frontend", + "call_pattern": "ProductCard.useEffect ([`ProductCard.tsx#L34`](../../opentelemetry-demo/src/frontend/components/ProductCard/ProductCard.tsx#L34)) → fetch(`/images/products/`) 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.", + "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 `` only resolves after that delay." + } + ], + "traces": [] + } +} diff --git a/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/test.sh b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d5-ic2-loadgeneratorfloodhomepage-on-univ00-universal_ttd60m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/environment/Dockerfile b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/environment/docker-compose.yaml b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/check_prediction.py b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubric.json b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubric.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/solve.py b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/solve.sh b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/check_prediction.py b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/expected.json b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..85e08dbb0530e481b4a5af59f5c4d8e9e18352a1 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/expected.json @@ -0,0 +1,14 @@ +{ + "events": [ + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-recommendationCacheFailure-on", + "root_cause": "recommendationCacheFailure", + "event_time": "2026-04-24T17:20:00.552300+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/test.sh b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-03-medium_ttd480m_range30m_off+60m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/solve.py b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-admanualgc-on-univ00-universal_ttd480m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/environment/Dockerfile b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/environment/docker-compose.yaml b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/check_prediction.py b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/rubric.json b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/rubric.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/solve.py b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/solve.sh b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/check_prediction.py b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/expected.json b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..bbcfc621540f4fc0c39d1b1c3675249479630b9c --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/test.sh b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-05-easy_ttd480m_period_previous-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubric.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubric.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/solve.py b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/solve.sh b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/expected.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..20367a385d5956855de181f44aa65fc65c0d2ea1 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/expected.json @@ -0,0 +1,29 @@ +{ + "events": [ + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-recommendationCacheFailure-on", + "root_cause": "recommendationCacheFailure", + "event_time": "2026-04-24T17:20:00.552300+00:00" + }, + { + "event_id": "d6-big-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T17:50:09.830911+00:00" + }, + { + "event_id": "d6-big-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:20:18.481618+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/test.sh b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-cartfailure-on-univ00-universal_ttd60m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubric.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.py b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.sh b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/expected.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..3d8e664db68e7f73fa508cd4b39858ecfc2cb6fe --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,29 @@ +{ + "events": [ + { + "event_id": "d6-big-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T17:50:09.830911+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + }, + { + "event_id": "d6-big-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:20:18.481618+00:00" + }, + { + "event_id": "d6-big-paymentFailure-100%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:50:26.427575+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/test.sh b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/environment/Dockerfile b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/environment/docker-compose.yaml b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/check_prediction.py b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubric.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubric.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/solve.py b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/solve.sh b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/check_prediction.py b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/expected.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..3d8e664db68e7f73fa508cd4b39858ecfc2cb6fe --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/expected.json @@ -0,0 +1,29 @@ +{ + "events": [ + { + "event_id": "d6-big-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T17:50:09.830911+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + }, + { + "event_id": "d6-big-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:20:18.481618+00:00" + }, + { + "event_id": "d6-big-paymentFailure-100%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:50:26.427575+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/test.sh b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-paymentfailure-10-02-medium_ttd480m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/environment/Dockerfile b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/environment/docker-compose.yaml b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/check_prediction.py b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/solve.py b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/solve.sh b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/check_prediction.py b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/expected.json b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/test.sh b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/environment/Dockerfile b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/environment/docker-compose.yaml b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/check_prediction.py b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubric.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubric.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/solve.py b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/solve.sh b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/check_prediction.py b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/expected.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9a2d21c5c81ab98071cf038d35aeff34d19e3db1 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/expected.json @@ -0,0 +1,29 @@ +{ + "events": [ + { + "event_id": "d6-big-paymentFailure-100%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:50:26.427575+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + }, + { + "event_id": "d6-big-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T17:50:09.830911+00:00" + }, + { + "event_id": "d6-big-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:20:18.481618+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/test.sh b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-01-hard_ttd15m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubric.json b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/solve.py b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/solve.sh b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/expected.json b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..55c6b7f958064978005e7a0583cbd7d84fefcca5 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d6-big-paymentFailure-100%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:50:26.427575+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/test.sh b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-paymentfailure-100-03-medium_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/environment/Dockerfile b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/environment/docker-compose.yaml b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/check_prediction.py b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubric.json b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubric.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/solve.py b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/solve.sh b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/check_prediction.py b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/expected.json b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..b0c37f0db4fda1b3c7c5d8896bab4305d3263933 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d6-big-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:20:18.481618+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T17:50:09.830911+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/test.sh b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-paymentfailure-50-03-easy_ttd1440m_day_same-day/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/environment/Dockerfile b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/environment/docker-compose.yaml b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/check_prediction.py b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubric.json b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubric.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/solve.py b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/solve.sh b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/check_prediction.py b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/expected.json b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..69628b1e6dbca7324adff9494eeca6aa2c9fa226 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/expected.json @@ -0,0 +1,19 @@ +{ + "events": [ + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + }, + { + "event_id": "d6-big-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T17:50:09.830911+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/test.sh b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-01-hard_ttd60m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/environment/Dockerfile b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/environment/docker-compose.yaml b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/check_prediction.py b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/rubric.json b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/rubric.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/solve.py b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/solve.sh b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/check_prediction.py b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/expected.json b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..100076c1294fd4f81f8ffb8e78628d43fe76c573 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/expected.json @@ -0,0 +1,9 @@ +{ + "events": [ + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/test.sh b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-05-easy_ttd480m_range30m_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/environment/Dockerfile b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/environment/docker-compose.yaml b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/check_prediction.py b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/solve.py b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/solve.sh b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/check_prediction.py b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/expected.json b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc4cc5173e2f9a3000b617f1fa0684868434823 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/expected.json @@ -0,0 +1,3 @@ +{ + "events": [] +} \ No newline at end of file diff --git a/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/test.sh b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-productcatalogfailure-on-06-medium_control_pre60m_at/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubric.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubric.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/solve.py b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/solve.sh b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/expected.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f1fe2b6f565398c2f2690386f3d77f6c34b9e69c --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/expected.json @@ -0,0 +1,14 @@ +{ + "events": [ + { + "event_id": "d6-big-recommendationCacheFailure-on", + "root_cause": "recommendationCacheFailure", + "event_time": "2026-04-24T17:20:00.552300+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/test.sh b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd15m_at_off+10m/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/environment/Dockerfile b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..437973f83ef89536fafbb7d7003eea4aa1814703 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/environment/Dockerfile @@ -0,0 +1 @@ +FROM ag2435/sre-otel-snapshot:{code_tag} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4202b28f14f099057e3516a27337e83e137b4b2 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/environment/docker-compose.yaml @@ -0,0 +1,21 @@ +services: + main: + build: + context: ${CONTEXT_DIR} + pull: true + image: ${MAIN_IMAGE_NAME} + command: [ "sh", "-c", "sleep infinity" ] + privileged: true + environment: + - TEST_DIR=${TEST_DIR} + - CONTEXT_DIR=${CONTEXT_DIR} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${CONTEXT_DIR}:${CONTEXT_DIR} + - ${HOST_VERIFIER_LOGS_PATH}:${ENV_VERIFIER_LOGS_PATH} + - ${HOST_AGENT_LOGS_PATH}:${ENV_AGENT_LOGS_PATH} + deploy: + resources: + limits: + cpus: ${CPUS} + memory: ${MEMORY} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubric.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubric.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubric.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/solve.py b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..02203432694be8598572c7e79e92e3920155b458 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/solve.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Generate an incident report from a rubric JSON via LLM. + +Standalone script designed to run inside a Harbor task container. +Also importable by ``run_solve.py`` for local batch generation. + +Examples:: + + # Inside Harbor container (solve.sh calls this): + python solve.py --rubric /tests/rubric.json --output /app/report.md + + # With custom model/effort: + python solve.py --rubric /tests/rubric.json --output /app/report.md -m openai-gpt-5.4 -e high +""" + +import argparse +import asyncio +import json +import logging +import os +from pathlib import Path +from typing import Any + +from check_prediction import async_call_llm_judge, format_rubric + +logger = logging.getLogger(__name__) + +DEFAULT_MODEL: str | None = None +DEFAULT_EFFORT = "high" + +# Report format from harbor-template/instruction.md.template — sections 1-4. +REPORT_FORMAT = """\ +Write a structured incident report with four sections: Summary, Timeline, \ +5 Whys, and Remediation. Follow all section-specific rules below. + +--- + +## Section 1: Summary + +2-3 sentences describing what happened, when, and the high-level impact. \ +This should be understandable by someone unfamiliar with the system. Focus \ +on what DID happen and the observable impact — mention request failures if \ +they occurred, but do NOT mention the absence of failures or errors as this \ +can be misread and cause confusion. You may name the root cause in a single \ +phrase (e.g. "due to a misconfigured batch job") but do not explain the \ +causal chain — that belongs in the 5 Whys section. + +Example: "Between 13:00 and 13:11 UTC on April 2, the order service returned \ +503 errors for 14% of checkout requests, affecting paying users, due to a \ +Redis cache eviction. The full causal chain is detailed in the 5 Whys section \ +below." + +--- + +## Section 2: Timeline + +A chronological narrative of ONLY what went wrong, reconstructed from the \ +provided telemetry. Each entry should be a single succinct line. Cover \ +higher-level events — when a change was introduced, when symptoms started, \ +when a change was reverted, when symptoms subsided — not individual error \ +occurrences. The first entry should be the earliest anomaly visible in the \ +provided telemetry; this establishes the incident start time referenced by \ +the Summary and 5 Whys sections. + +For each entry: +- State the time (UTC), the service(s) involved, and what happened +- Quantify where possible (error rate, duration, number of affected requests) +- Do NOT include normal/healthy behavior, baseline noise, or things that \ +worked correctly + +Example format: +``` +09:44 UTC — analytics-job deployed with no memory limit set +14:17 UTC — redis-cache-0 OOMKilled; node memory at 97% +14:18 UTC — inventory-svc cache misses begin; all requests fall through to Postgres +14:18 UTC — order-svc goroutine pool exhaustion begins; 503 error rate climbs to 14% +14:29 UTC — redis-cache-0 rescheduled; error rate returns to baseline +``` + +--- + +## Section 3: 5 Whys + +Rules: +1. Start by stating the problem as a precise, observable symptom — not a \ +cause. Include what failed, when, and impact (error rate, affected users, \ +duration). +2. Each "why" answer must be grounded in the provided telemetry. Cite only \ +the telemetry types relevant to that step, using the format below for each. + + - Metrics: one sentence describing the baseline value (or typical range), \ +what it changed to, and at what UTC timestamp. Where relevant, include rate \ +of change or duration. Follow with the exact PromQL query that would surface it. + Example — "Error rate on order-svc was 0.1% at 14:17 UTC, jumping to \ +14% at 14:18 UTC. PromQL: rate(http_requests_total{service="order-svc",\ +status=~"5.."}[1m])" + + - Traces: the cascade from the highest-level operation down to the deepest \ +failing span, followed by representative trace IDs from the provided data. + Example — "checkout request → order-svc goroutine exhaustion → \ +inventory-svc Redis GET timeout. Trace IDs: 4bf92f3577b34da6, a3ce929d0e0e4736" + + - Logs: one sentence with service, endpoint, error, and time range, \ +followed by the exact Lucene query that would retrieve the relevant log lines. + Example — "Between 14:18:02 and 14:29:11 UTC, POST /api/checkout \ +returned 503s. Lucene: service:order-svc AND status:503 AND \ +endpoint:\\"/api/checkout\\"" +3. Each "why" targets the previous answer, not the original problem. Drill \ +down one causal chain; do not branch. +4. Never accept "human error" or "operator mistake" as a terminal answer. \ +Ask why the human was in a position to make that error. +5. Stop when you reach a cause that is: (a) actionable — something a team \ +can change, or (b) a process or system gap that allowed the failure to \ +propagate. The number of steps is not fixed at 5. +6. Only include steps that are directly supported by the provided telemetry. \ +If the causal chain cannot be completed with the available evidence, stop \ +and note what additional telemetry would be needed to continue. +7. After the chain, note any branches you did NOT follow. If the incident \ +has multiple contributing causes that cannot fit a single chain, say so \ +explicitly rather than forcing one. + +Output format: + +``` +Problem statement: +[Observable symptom with time, impact, and detection method] + +Why 1: [question] → [answer] +Evidence: [specific signal] + +Why 2: [question] → [answer] +Evidence: [specific signal] + +... + +Root cause: +[Single sentence naming the systemic or process failure] + +Unexplored branches: +[Contributing factors visible in telemetry that were not followed, \ +and why they were set aside] +``` + +--- + +## Section 4: Remediation + +For each corrective action, identify which step in the causal chain it \ +targets and what class of fix it is: + +- **Root cause fix**: eliminates the condition that started the chain +- **Propagation fix**: limits blast radius if the root cause recurs +- **Detection fix**: reduces time-to-detect or time-to-mitigate + +List actions from root cause outward. Prefer fixes that prevent recurrence \ +over fixes that only improve response. + +Output format: + +| Action | Targets | Type | +|--------|---------|------| +| [What to do] | Why N | Root cause fix / Propagation fix / Detection fix | +""" + +SOLUTION_PROMPT_TEMPLATE = """\ +You are an expert site reliability engineer. You are given a ground-truth \ +rubric describing an incident's root cause, mechanism, and telemetry evidence. + +Your task: write an incident report as if you investigated this incident \ +yourself. Use the rubric evidence to populate each section. Do NOT mention \ +the rubric or that you were given ground-truth data — write as though you \ +discovered everything through telemetry analysis. + +## Ground-Truth Rubric + +{rubric} + +## Report Format + +{report_format} +""" + + +def build_solution_prompt(rubric_md: str) -> str: + """Build the LLM prompt from a formatted rubric markdown string.""" + return SOLUTION_PROMPT_TEMPLATE.format( + rubric=rubric_md, + report_format=REPORT_FORMAT, + ) + + +async def generate_report( + client: Any, + rubric_data: dict, + model: str | None = DEFAULT_MODEL, + effort: str | None = DEFAULT_EFFORT, +) -> tuple[str, str, list[dict] | None]: + """Generate an incident report from rubric JSON. + + If ``model`` is ``None``, the formatted rubric is returned directly with + no LLM call. Otherwise the rubric is passed to the LLM to be reformatted + into an incident report. + + Returns: + A tuple of (report_text, prompt, reasoning_summary). When ``model`` + is ``None``, ``prompt`` is empty and ``reasoning_summary`` is ``None``. + + """ + rubric_md = format_rubric(rubric_data) + if model is None: + return rubric_md, "", None + prompt = build_solution_prompt(rubric_md) + response_text, reasoning_summary = await async_call_llm_judge( + client, prompt, model=model, reasoning_effort=effort + ) + return response_text, prompt, reasoning_summary + + +async def async_main() -> None: + """CLI entry point: read rubric, call LLM, write report.""" + parser = argparse.ArgumentParser( + description="Generate an incident report from a rubric JSON via LLM." + ) + parser.add_argument( + "--rubric", + type=str, + default="/tests/rubric.json", + help="Path to rubric JSON file.", + ) + parser.add_argument( + "--output", + type=str, + default="/app/report.md", + help="Path to write the generated report.", + ) + parser.add_argument( + "--model", + "-m", + type=str, + default=DEFAULT_MODEL, + help=( + "LLM model name. If omitted, the formatted rubric is written " + "directly as the report with no LLM call." + ), + ) + parser.add_argument( + "--effort", + "-e", + type=str, + choices=["low", "medium", "high"], + default=DEFAULT_EFFORT, + help=f"Reasoning effort level (default: {DEFAULT_EFFORT}).", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + rubric_path = Path(args.rubric) + output_path = Path(args.output) + + if not rubric_path.is_file(): + logger.warning(f"Rubric file not found: {rubric_path}; writing empty report") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text("") + return + + rubric_data = json.loads(rubric_path.read_text()) + logger.info( + f"Loaded rubric: {rubric_data.get('feature_flag', 'unknown')} " + f"from {rubric_path}" + ) + + client: Any = None + if args.model is not None: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + + report_text, _prompt, reasoning_summary = await generate_report( + client, rubric_data, model=args.model, effort=args.effort + ) + + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(report_text) + logger.info(f"Wrote report to {output_path}") + + if reasoning_summary: + logger.info(f"Reasoning summary: {reasoning_summary}") + + +if __name__ == "__main__": + asyncio.run(async_main()) diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/solve.sh b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e35518cfd193a74029d324b30c84e1e1f372c6f8 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/solution/solve.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +# ── Wait for the entrypoint to finish setting up the environment ── +echo "[solve] Waiting for environment to be ready..." +for i in $(seq 1 180); do + [ -f /tmp/env-ready ] && break + sleep 1 +done +if [ ! -f /tmp/env-ready ]; then + echo "[solve] ERROR: Environment did not become ready within 180s" >&2 + exit 1 +fi +echo "[solve] Environment is ready." + +# ── Verify all services are healthy ── +echo "[solve] Running health checks..." +source /tmp/env-ports +/app/check_health.sh || { + echo "[solve] ERROR: Health checks failed" >&2 + exit 1 +} + +# ── Generate solution report via LLM ── +echo "[solve] Installing dependencies..." +pip install tabulate +echo "[solve] Generating report..." +python /solution/solve.py --rubric /solution/rubric.json diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bafdc4793dd9251a375665122753243f1b56eb --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/check_prediction.py @@ -0,0 +1,1005 @@ +"""LLM-as-a-judge verifier for Harbor incident-RCA-report tasks. + +Supports two modes: + +1. **Harbor verifier** (default): + python /tests/check_prediction.py + +2. **Post-hoc single-trial**: + python check_prediction.py --expected expected.json --predictions report.md [--rubric rubric.json] + +Falls back to string-match scoring when OPENAI_API_KEY is not set. +""" + +import argparse +import asyncio +import json +import logging +import os +import sys +import traceback +from pathlib import Path +from typing import Any + +from tabulate import tabulate + +logger = logging.getLogger(__name__) + +JUDGE_PROMPT_MULTI_HEADER = """\ +You are an expert SRE tasked with judging the quality of an AI-generated incident RCA report. + +You are given: +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. +2. The SRE agent's incident RCA report. + +## SRE Agent's Incident RCA Report + +{predictions} + +## Ground-Truth Rubrics + +{rubrics} + +## Evaluation Questions + +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. + +For each rubric: + +- `incident_time_within_10min`: Did the agent's timeline place the incident start within ±10 minutes of this rubric's `incident_time`? +- `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.) +- `mechanism_match`: Did the agent correctly explain this rubric's mechanism — how the flag propagates to the user-visible failure? +- For each metric/log/trace cluster listed for this rubric: per-cluster match flags as before. +""" + +JUDGE_PROMPT_SCORING_FOOTER = """\ + +## Overall Score + +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. + +- 0: AI findings are misaligned with every rubric's mechanism and completely miss the root cause +- 1: AI verifies incident description — the report confirms symptoms described in the task prompt but does not investigate further +- 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 +- 3: AI nails at least one of the listed root causes — the report correctly identifies it, the mechanism, and the supporting signals + +Respond with ONLY a JSON object matching the provided output schema. +""" + +DEFAULT_MODEL = "openai-gpt-5.4" + + +# --------------------------------------------------------------------------- +# Rubric rendering (JSON -> markdown) +# --------------------------------------------------------------------------- + + +def _format_log_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render log clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} entries)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + source = cluster.get("source", "") + if source: + lines.append(f"**Source:** {source}") + lines.append("") + + attrs = cluster.get("representative_attributes", {}) + if attrs: + lines.append("**Representative attributes:**") + lines.append("") + rows = [[f"`{k}`", f"`{v}`"] for k, v in attrs.items()] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + docs = cluster.get("log_documents", []) + if docs: + lines.append("**Log documents:**") + lines.append("") + rows = [ + [f"`{d['_index']}`", f"`{d['_id']}`", d["@timestamp"]] for d in docs + ] + lines.append( + tabulate( + rows, headers=["_index", "_id", "@timestamp"], tablefmt="github" + ) + ) + lines.append("") + + +def _format_trace_clusters(clusters: list[dict], lines: list[str]) -> None: + """Render trace clusters as markdown subsections.""" + for cluster in clusters: + name = cluster.get("name", "Unknown") + count = cluster.get("count") + suffix = f" ({count} traces)" if count is not None else "" + lines.append(f"#### {name}{suffix}") + lines.append("") + + description = cluster.get("description", "") + if description: + lines.append(description) + lines.append("") + + cause = cluster.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + call_chain = cluster.get("call_chain", "") + if call_chain: + lines.append("**Call chain:**") + lines.append("") + lines.append("```") + lines.append(call_chain) + lines.append("```") + lines.append("") + + smoking_gun = cluster.get("smoking_gun", []) + if smoking_gun: + lines.append("**Smoking-gun error messages:**") + lines.append("") + for msg in smoking_gun: + lines.append(f"- {msg}") + lines.append("") + + docs = cluster.get("trace_documents", []) + if docs: + lines.append("**Trace documents:**") + lines.append("") + headers = ["traceID", "@timestamp"] + has_action = any("user_action" in d for d in docs) + if has_action: + headers.append("user_action") + rows = [] + for d in docs: + row = [f"`{d['traceID']}`", d["@timestamp"]] + if has_action: + row.append(d.get("user_action", "")) + rows.append(row) + lines.append(tabulate(rows, headers=headers, tablefmt="github")) + lines.append("") + + +_LAYER_DESCRIPTIONS = { + "root_cause": "metric closest to the fault injection point", + "propagation": "intermediate services reflecting the error through the call chain", + "symptom": "user-facing impact visible to end users or clients", + "meta": "feature flag counters or internal plumbing", + "unknown": "unclassified", +} + +_LAYER_ORDER = ["root_cause", "propagation", "symptom", "meta", "unknown"] + + +def _format_onset(offset: int | None) -> str: + """Format an onset offset as '+Xs' or 'N/A'.""" + if offset is None: + return "N/A" + return f"+{offset}s" + + +def _format_label_values(labels: dict[str, str]) -> str: + """Format label values as a compact comma-separated string.""" + if not labels: + return "" + return ", ".join(labels.values()) + + +def _earliest_onset(variants: list[dict]) -> int | None: + """Return the earliest onset_offset_seconds across variants, or None.""" + offsets = [ + v["onset_offset_seconds"] + for v in variants + if v.get("onset_offset_seconds") is not None + ] + return min(offsets) if offsets else None + + +def _format_metrics_list(metrics_list: list[dict], lines: list[str]) -> None: + """Render metric families grouped by signal layer.""" + by_layer: dict[str, list[dict]] = {} + for fam in metrics_list: + by_layer.setdefault(fam.get("signal_layer", "unknown"), []).append(fam) + + for layer in _LAYER_ORDER: + layer_families = by_layer.get(layer, []) + if not layer_families: + continue + + layer_onsets = [_earliest_onset(f["variants"]) for f in layer_families] + layer_onsets = [o for o in layer_onsets if o is not None] + layer_onset_str = ( + f" (earliest onset: {_format_onset(min(layer_onsets))})" + if layer_onsets + else "" + ) + + display_layer = layer.replace("_", " ").title() + desc = _LAYER_DESCRIPTIONS.get(layer, "") + lines.append(f"**{display_layer}** — {desc}{layer_onset_str}") + lines.append("") + + for fam in layer_families: + fam_onset = _earliest_onset(fam["variants"]) + label_vals = _format_label_values(fam.get("defining_labels", {})) + label_part = f" ({label_vals})" if label_vals else "" + lines.append( + f"#### {fam['metric_family']} family{label_part}" + f" — onset: {_format_onset(fam_onset)}" + ) + lines.append("") + + first_desc = ( + fam["variants"][0].get("description", "") if fam["variants"] else "" + ) + if first_desc: + lines.append(first_desc) + lines.append("") + + for v in fam["variants"]: + v_onset = _format_onset(v.get("onset_offset_seconds")) + lines.append(f"- **{v['type']}** (onset: {v_onset})") + lines.append(f" `{v['query']}`") + lines.append("") + + +def _format_frontend_issues(issues: list[dict], lines: list[str]) -> None: + """Render frontend issues as markdown subsections.""" + for issue in issues: + route = issue.get("route", "Unknown route") + lines.append(f"#### {route}") + lines.append("") + + description = issue.get("description", "") + if description: + lines.append(description) + lines.append("") + + rows = [ + ["Deterministic", str(issue.get("deterministic", ""))], + ["Trigger condition", issue.get("trigger_condition", "")], + ["Calling service", issue.get("calling_service", "")], + [ + "Source", + f"`{issue.get('source_file', '')}:{issue.get('source_line', '')}`", + ], + ] + lines.append(tabulate(rows, headers=["Field", "Value"], tablefmt="github")) + lines.append("") + + call_pattern = issue.get("call_pattern", "") + if call_pattern: + lines.append(f"**Call pattern:** {call_pattern}") + lines.append("") + + cause = issue.get("cause", "") + if cause: + lines.append(f"**Cause:** {cause}") + lines.append("") + + +def format_rubric(data: dict, include_frontend: bool = False) -> str: + """Convert a rubric JSON dict into a consistently formatted markdown string. + + Args: + data: The rubric JSON dict. + include_frontend: If True, include the ``### Frontend`` section. + Defaults to False since frontend symptoms may be noisy for + downstream consumers (LLM judge, oracle solutions). + TODO(Albert): systematically test the impact of including vs. + excluding frontend symptoms on downstream consumers. + + """ + lines: list[str] = [] + + lines.append(f"# {data['feature_flag']}") + lines.append("") + lines.append(f"**Feature flag:** `{data['feature_flag']}`") + lines.append("") + lines.append(f"**Description:** {data['description']}") + lines.append("") + lines.append(f"**Incident time:** {data['incident_time']}") + lines.append("") + + lines.append("## Mechanism") + lines.append("") + lines.append(data["mechanism"]) + lines.append("") + + interaction = data.get("interaction", "") + if interaction: + lines.append(f"**Interaction with other feature flags:** {interaction}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + + gs = data["symptoms"] + + metrics = gs.get("metrics", []) + lines.append("### Metrics") + lines.append("") + if metrics: + _format_metrics_list(metrics, lines) + + logs = gs.get("logs", []) + lines.append("### Logs") + lines.append("") + if logs: + _format_log_clusters(logs, lines) + + if include_frontend: + frontend = gs.get("frontend", []) + lines.append("### Frontend") + lines.append("") + if frontend: + _format_frontend_issues(frontend, lines) + + traces = gs.get("traces", []) + lines.append("### Traces") + lines.append("") + if traces: + _format_trace_clusters(traces, lines) + + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Judge prompt + output-schema builders +# --------------------------------------------------------------------------- + + +def _render_checklist(rubric_data: dict) -> str: + """Build per-cluster checklist blocks for metrics/logs/traces.""" + symptoms = rubric_data.get("symptoms", {}) or {} + metric_clusters = symptoms.get("metrics", []) or [] + log_clusters = symptoms.get("logs", []) or [] + trace_clusters = symptoms.get("traces", []) or [] + + blocks: list[str] = [] + + if metric_clusters: + lines = ["#### Metric clusters"] + for i, m in enumerate(metric_clusters): + family = m.get("metric_family", "") + lines.append( + f'- Cluster {i}: `metric_family = "{family}"`' + f" — family_match: did the agent cite a query targeting" + f" metric_family `{family}` under a Why-step whose causal chain" + f" aligns with the rubric?" + ) + blocks.append("\n".join(lines)) + + if log_clusters: + lines = ["#### Log clusters"] + for i, log in enumerate(log_clusters): + attrs = log.get("representative_attributes") or {} + body = attrs.get("body", "") + service_name = attrs.get("resource.service.name", "") + lines.append( + f"- Cluster {i}:\n" + f" - `resource.service.name`: `{service_name}`\n" + f" - `body`: `{body}`\n" + f" - body_match: did the agent cite log evidence whose body" + f" matches the rubric's `body` under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - service_name_match: did the agent attribute the cited" + f" log evidence to the OTel service `{service_name}`" + f" (`resource.service.name`)?" + ) + blocks.append("\n".join(lines)) + + if trace_clusters: + lines = ["#### Trace clusters"] + for i, trace in enumerate(trace_clusters): + call_chain = trace.get("call_chain", "") + smoking_gun = trace.get("smoking_gun", []) or [] + sg_rendered = "\n".join(f" - {s}" for s in smoking_gun) + lines.append( + f"- Cluster {i}:\n" + f" - call_chain: `{call_chain}`\n" + f" - smoking_gun:\n{sg_rendered}\n" + f" - call_chain_match: did the agent cite evidence matching" + f" this service-level call chain under a Why-step whose causal" + f" chain aligns with the rubric?\n" + f" - smoking_gun_match: did the agent cite at least one of" + f" the listed smoking-gun signals?" + ) + blocks.append("\n".join(lines)) + + return ( + "\n\n".join(blocks) + if blocks + else "(No metric, log, or trace clusters in rubric.)" + ) + + +def build_judge_prompt( + rubrics_data: list[dict], + predictions: str, +) -> str: + """Render the judge prompt for one or more ground-truth rubrics. + + The prompt asks the LLM to evaluate the agent's report against **each** + rubric independently. The agent is credited if it correctly identifies + any one rubric (the overall score reflects the best match). + """ + if not rubrics_data: + raise ValueError("build_judge_prompt called with no rubrics") + + rubric_blocks: list[str] = [] + checklist_blocks: list[str] = [] + for i, rubric in enumerate(rubrics_data): + feature_flag = rubric.get("feature_flag", "") + rubric_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + format_rubric(rubric) + ) + checklist_blocks.append( + f"### Rubric {i + 1} of {len(rubrics_data)} — `{feature_flag}`\n\n" + + _render_checklist(rubric) + ) + + rubrics_text = "\n\n---\n\n".join(rubric_blocks) + checklist_text = "\n\n---\n\n".join(checklist_blocks) + + header = JUDGE_PROMPT_MULTI_HEADER.format( + rubrics=rubrics_text, + predictions=predictions, + ) + return header + "\n" + checklist_text + "\n" + JUDGE_PROMPT_SCORING_FOOTER + + +_METRIC_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "metric_family": {"type": "string"}, + "family_match": {"type": "boolean"}, + }, + "required": ["metric_family", "family_match"], + "additionalProperties": False, +} + +_LOG_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "body_match": {"type": "boolean"}, + "service_name_match": {"type": "boolean"}, + }, + "required": ["body_match", "service_name_match"], + "additionalProperties": False, +} + +_TRACE_ITEM_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "call_chain_match": {"type": "boolean"}, + "smoking_gun_match": {"type": "boolean"}, + }, + "required": ["call_chain_match", "smoking_gun_match"], + "additionalProperties": False, +} + + +_PER_RUBRIC_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "feature_flag": {"type": "string"}, + "incident_time_within_10min": {"type": "boolean"}, + "feature_flag_match": {"type": "boolean"}, + "mechanism_match": {"type": "boolean"}, + "symptoms": { + "type": "object", + "properties": { + "metrics": {"type": "array", "items": _METRIC_ITEM_SCHEMA}, + "logs": {"type": "array", "items": _LOG_ITEM_SCHEMA}, + "traces": {"type": "array", "items": _TRACE_ITEM_SCHEMA}, + }, + "required": ["metrics", "logs", "traces"], + "additionalProperties": False, + }, + }, + "required": [ + "feature_flag", + "incident_time_within_10min", + "feature_flag_match", + "mechanism_match", + "symptoms", + ], + "additionalProperties": False, +} + + +def build_judge_output_schema(rubrics_data: list[dict]) -> dict: + """Build a strict JSON Schema for the judge output: one verdict per rubric + + an overall ``score`` integer. Falls back to a minimal ``{score: int}`` + schema when no rubrics are supplied (no-incident path). + + Per-rubric cluster-array lengths vary across rubrics; rather than encode + a per-element schema (which Structured Outputs doesn't support), we leave + the array lengths unconstrained and rely on the prompt instructions to + keep cluster order matching. + """ + if not rubrics_data: + return { + "type": "object", + "properties": {"score": {"type": "integer"}}, + "required": ["score"], + "additionalProperties": False, + } + + n = len(rubrics_data) + return { + "type": "object", + "properties": { + "rubrics": { + "type": "array", + "minItems": n, + "maxItems": n, + "items": _PER_RUBRIC_SCHEMA, + }, + "score": {"type": "integer"}, + }, + "required": ["rubrics", "score"], + "additionalProperties": False, + } + + +# --------------------------------------------------------------------------- +# API call +# --------------------------------------------------------------------------- + + +async def async_call_llm_judge( + client: Any, + prompt: str, + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, + output_schema: dict | None = None, +) -> tuple[str, list[dict] | None]: + """Call the LLM judge via the OpenAI Responses API (falling back to Chat). + + When ``output_schema`` is provided, uses Structured Outputs (strict JSON + Schema) so the returned text is guaranteed to conform to the schema. + + Returns: + A tuple of (output_text, reasoning_summaries). reasoning_summaries is + None when reasoning_effort is not set. + + """ + text_format: dict[str, Any] = ( + { + "type": "json_schema", + "name": "judge_response", + "schema": output_schema, + "strict": True, + } + if output_schema is not None + else {"type": "text"} + ) + try: + kwargs: dict[str, Any] = { + "model": model, + "input": prompt, + "text": {"format": text_format}, + "tools": [], + "store": True, + "max_output_tokens": 16384, + } + if reasoning_effort is not None: + kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"} + response = await client.responses.create(**kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_summaries = [ + [ + s.model_dump() if hasattr(s, "model_dump") else s + for s in item.summary + ] + for item in response.output + if getattr(item, "type", None) == "reasoning" + and getattr(item, "summary", None) is not None + ] + return response.output_text, reasoning_summaries + except Exception as exc: + if "404" not in str(exc): + raise + logger.info( + f"Responses API returned 404 for {model}, falling back to Chat Completions" + ) + chat_kwargs: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "max_tokens": 16384, + } + if output_schema is not None: + chat_kwargs["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": "judge_response", + "schema": output_schema, + "strict": True, + }, + } + if reasoning_effort is not None: + chat_kwargs["reasoning_effort"] = reasoning_effort + response = await client.chat.completions.create(**chat_kwargs) + reasoning_summaries = None + if reasoning_effort is not None: + reasoning_content = getattr( + response.choices[0].message, "reasoning_content", None + ) + if reasoning_content is not None: + reasoning_summaries = [{"type": "text", "text": reasoning_content}] + else: + reasoning_summaries = [] + return response.choices[0].message.content, reasoning_summaries + + +# --------------------------------------------------------------------------- +# Parsing + aggregation +# --------------------------------------------------------------------------- + + +def parse_judge_response(response_text: str) -> dict: + """Parse the judge response JSON and range-check ``score``. + + When Structured Outputs are used upstream, the response is already + schema-validated; this function only decodes the JSON and enforces the + 0-3 range for ``score``. + """ + parsed = json.loads(response_text) + score = int(parsed["score"]) + if score < 0 or score > 3: + raise ValueError(f"Score {score} out of range [0, 3]") + parsed["score"] = score + return parsed + + +def _aggregate_one_rubric(verdict: dict) -> dict: + """Roll up cluster verdicts for a single per-rubric judge entry.""" + symptoms = verdict.get("symptoms", {}) or {} + metrics = symptoms.get("metrics", []) or [] + logs = symptoms.get("logs", []) or [] + traces = symptoms.get("traces", []) or [] + + metric_hits = [bool(m.get("family_match")) for m in metrics] + log_hits = [ + bool(l.get("body_match")) and bool(l.get("service_name_match")) for l in logs + ] + trace_hits = [ + bool(t.get("call_chain_match")) and bool(t.get("smoking_gun_match")) + for t in traces + ] + + def _all(hits: list[bool]) -> bool | None: + return all(hits) if hits else None + + def _any(hits: list[bool]) -> bool | None: + return any(hits) if hits else None + + return { + "feature_flag": verdict.get("feature_flag", ""), + "incident_time_within_10min": bool(verdict.get("incident_time_within_10min")), + "feature_flag_match": bool(verdict.get("feature_flag_match")), + "mechanism_match": bool(verdict.get("mechanism_match")), + "metrics_all_match": _all(metric_hits), + "metrics_any_match": _any(metric_hits), + "logs_all_match": _all(log_hits), + "logs_any_match": _any(log_hits), + "traces_all_match": _all(trace_hits), + "traces_any_match": _any(trace_hits), + } + + +def aggregate_judge_response(parsed: dict) -> dict: + """Aggregate per-rubric, per-cluster verdicts into flat any-of rollups. + + The agent is credited if it matches any one of the listed rubrics. + Per-rubric rollups are computed via ``_aggregate_one_rubric``; the + task-level rollup is the ``any`` over rubrics for booleans (with ``None`` + skipped — sections without clusters in any rubric stay ``None``). + + The per-rubric rollups are also returned under ``per_rubric`` for + downstream analysis that needs to know which specific rubric matched. + """ + rubrics = parsed.get("rubrics") or [] + per_rubric = [_aggregate_one_rubric(r) for r in rubrics] + + def _any_skip_none(values: list[bool | None]) -> bool | None: + truthy = [v for v in values if v is not None] + return any(truthy) if truthy else None + + return { + "incident_time_within_10min": _any_skip_none( + [r["incident_time_within_10min"] for r in per_rubric] + ) + or False, + "feature_flag_match": _any_skip_none( + [r["feature_flag_match"] for r in per_rubric] + ) + or False, + "mechanism_match": _any_skip_none([r["mechanism_match"] for r in per_rubric]) + or False, + "metrics_all_match": _any_skip_none( + [r["metrics_all_match"] for r in per_rubric] + ), + "metrics_any_match": _any_skip_none( + [r["metrics_any_match"] for r in per_rubric] + ), + "logs_all_match": _any_skip_none([r["logs_all_match"] for r in per_rubric]), + "logs_any_match": _any_skip_none([r["logs_any_match"] for r in per_rubric]), + "traces_all_match": _any_skip_none([r["traces_all_match"] for r in per_rubric]), + "traces_any_match": _any_skip_none([r["traces_any_match"] for r in per_rubric]), + "per_rubric": per_rubric, + "score": int(parsed["score"]), + } + + +def string_match_fallback(expected: dict, predictions: str) -> dict: + """Fall back to case-insensitive string search for any plausible root_cause. + + ``expected["events"]`` is a list of ``{"root_cause": , "event_time": ...}``; + the agent's report is credited if any listed root_cause appears in it. + Returns a result dict compatible with the judge output format. + """ + events: list[dict] = expected.get("events") or [] + if not events: + # No-incident task: agent should write an empty report. + return {"score": 3 if len(predictions.strip()) == 0 else 0} + text = predictions.lower() + found = any(e["root_cause"].strip().lower() in text for e in events) + return {"score": 3 if found else 0} + + +# --------------------------------------------------------------------------- +# Judge entry point (used by both modes) +# --------------------------------------------------------------------------- + + +async def judge( + client: Any, + expected: dict, + predictions: str, + rubrics_data: list[dict], + model: str = DEFAULT_MODEL, + reasoning_effort: str | None = None, +) -> dict: + """Run the LLM judge over one or more ground-truth rubrics, or + short-circuit for no-incident tasks. + + Returns: + A dict with keys: reward, mode, score, and (for LLM judge) model, + nested (raw judge response), reasoning_summary, rubric_used, + judge_prompt, judge_response_raw. Per-section rollups are derived + post-hoc from ``nested`` by formatters via ``aggregate_judge_response``. + + """ + events: list[dict] = expected.get("events") or [] + if not events: + score = 3 if len(predictions.strip()) == 0 else 0 + return { + "reward": score / 3.0, + "mode": "no_incident", + "model": model, + "score": score, + } + + # Short-circuit when the agent emitted an empty report despite an incident. + # No LLM call can rescue this; score is a guaranteed 0. We synthesize the + # nested response shape (per-rubric all False, matching cluster counts) + # so that ``aggregate_judge_response`` produces the expected all-False + # rollups at load time. + if not predictions.strip(): + synthetic_per_rubric = [] + for rubric in rubrics_data: + symptoms = rubric.get("symptoms", {}) or {} + synthetic_per_rubric.append( + { + "feature_flag": rubric.get("feature_flag", ""), + "incident_time_within_10min": False, + "feature_flag_match": False, + "mechanism_match": False, + "symptoms": { + "metrics": [ + { + "metric_family": m.get("metric_family", ""), + "family_match": False, + } + for m in (symptoms.get("metrics") or []) + ], + "logs": [ + {"body_match": False, "service_name_match": False} + for _ in (symptoms.get("logs") or []) + ], + "traces": [ + {"call_chain_match": False, "smoking_gun_match": False} + for _ in (symptoms.get("traces") or []) + ], + }, + } + ) + return { + "mode": "empty_report", + "model": model, + "score": 0, + "reward": 0.0, + "rubric_used": bool(rubrics_data), + "nested": {"rubrics": synthetic_per_rubric, "score": 0}, + } + + prompt = build_judge_prompt(rubrics_data, predictions) + output_schema = build_judge_output_schema(rubrics_data) + + raw_response, reasoning_summary = await async_call_llm_judge( + client, + prompt, + model=model, + reasoning_effort=reasoning_effort, + output_schema=output_schema, + ) + parsed = parse_judge_response(raw_response) + + # Per-section rollups are NOT spread into the result — they're a pure + # post-hoc derivation from ``nested`` via ``aggregate_judge_response``, + # applied by the formatters at load time so schema changes don't require + # rewriting saved JSONs. + return { + "mode": "llm_judge", + "model": model, + "score": parsed["score"], + "reward": parsed["score"] / 3.0, + "reasoning_summary": reasoning_summary, + "rubric_used": bool(rubrics_data), + "judge_prompt": prompt, + "judge_response_raw": raw_response, + "nested": parsed, + } + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +async def main() -> None: + """Entry point: load expected + predictions, score, write reward/details.""" + parser = argparse.ArgumentParser( + description="LLM-as-a-judge verifier for Harbor incident-RCA-report tasks." + ) + parser.add_argument("--expected", type=str, default="/tests/expected.json") + parser.add_argument("--predictions", type=str, default="/app/report.md") + parser.add_argument( + "--rubrics-dir", + type=str, + default="/tests/rubrics", + help=( + "Directory containing one rubric JSON per plausible root cause " + "(e.g. /tests/rubrics/.json). The judge scores the " + "agent against any one of them." + ), + ) + parser.add_argument( + "--model", type=str, default=DEFAULT_MODEL, help="Judge LLM model name." + ) + parser.add_argument( + "--effort", + type=str, + choices=["low", "medium", "high"], + default="high", + help="Reasoning effort level for the judge LLM (default: high).", + ) + parser.add_argument( + "--mode", + type=str, + choices=["string_match", "llm_judge"], + default="string_match", + help="Scoring mode: string_match or llm_judge (default: string_match).", + ) + parser.add_argument("--reward", type=str, default="/logs/verifier/reward.txt") + parser.add_argument("--details", type=str, default="/logs/verifier/details.json") + args = parser.parse_args() + + expected_path = Path(args.expected) + predictions_path = Path(args.predictions) + rubrics_dir = Path(args.rubrics_dir) + reward_path = Path(args.reward) + details_path = Path(args.details) + + try: + # Load expected + print(f"Loading expected results from {expected_path}...") + with expected_path.open() as f: + expected = json.load(f) + + # Load predictions (markdown report) + print(f"Loading predictions from {predictions_path}...") + predictions = predictions_path.read_text() + + # Load rubric JSONs — one per plausible root cause. Order is the + # filesystem sort order, which matches the build_harbor_tasks.py + # naming convention (event_id stems sort lexicographically). + rubrics_data: list[dict] = [] + if expected.get("events"): + if rubrics_dir.is_dir(): + rubric_paths = sorted(rubrics_dir.glob("*.json")) + for p in rubric_paths: + with p.open() as f: + rubrics_data.append(json.load(f)) + print(f"Loaded {len(rubrics_data)} rubric(s) from {rubrics_dir}") + else: + print(f"Rubric directory missing: {rubrics_dir}") + else: + print("No incident events in expected results; skipping rubric load.") + + # Run judge + if args.mode == "string_match": + em = string_match_fallback(expected, predictions) + result = {"reward": em["score"] / 3.0, "mode": "string_match", **em} + else: + from openai import AsyncOpenAI + + client = AsyncOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("OPENAI_BASE_URL"), + ) + result = await judge( + client, + expected, + predictions, + rubrics_data, + model=args.model, + reasoning_effort=args.effort, + ) + + # Write reward + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text(str(result["reward"])) + + # Write details + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text(json.dumps(result, indent=2)) + + print(f"Score: {result.get('score', 'N/A')}/3 (reward: {result['reward']})") + print(f"Mode: {result['mode']}") + if result.get("reasoning_summary"): + print(f"Reasoning summary: {result['reasoning_summary']}") + + if result["reward"] < 1.0: + sys.exit(1) + + except Exception as exc: + reward_path.parent.mkdir(parents=True, exist_ok=True) + reward_path.write_text("0.0") + details_path.parent.mkdir(parents=True, exist_ok=True) + details_path.write_text( + json.dumps( + { + "reward": 0.0, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + }, + indent=2, + ) + ) + print(f"Verifier error: {type(exc).__name__}: {exc}") + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/expected.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..ed34707db40d83ef765405e5ede931c5568496e9 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/expected.json @@ -0,0 +1,34 @@ +{ + "events": [ + { + "event_id": "d6-big-recommendationCacheFailure-on", + "root_cause": "recommendationCacheFailure", + "event_time": "2026-04-24T17:20:00.552300+00:00" + }, + { + "event_id": "d6-big-productCatalogFailure-on", + "root_cause": "productCatalogFailure", + "event_time": "2026-04-24T17:04:56.642846+00:00" + }, + { + "event_id": "d6-big-cartFailure-on", + "root_cause": "cartFailure", + "event_time": "2026-04-24T17:35:06.626864+00:00" + }, + { + "event_id": "d6-big-paymentFailure-10%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T17:50:09.830911+00:00" + }, + { + "event_id": "d6-big-paymentFailure-50%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:20:18.481618+00:00" + }, + { + "event_id": "d6-big-paymentFailure-100%", + "root_cause": "paymentFailure", + "event_time": "2026-04-24T18:50:26.427575+00:00" + } + ] +} \ No newline at end of file diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-cartFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-cartFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..d0c351612e81ef6ced842ecc84c7b73909cbe495 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-cartFailure-on.json @@ -0,0 +1,315 @@ +{ + "incident_time": "2026-04-24T17:35:06.626864+00:00", + "feature_flag": "cartFailure", + "description": "A feature flag made `CartService.EmptyCartAsync` route through `_badCartStore`, a `ValkeyCartStore` wired to the unreachable host `badhost:1234`; the connection attempt threw `SocketException`, was rewrapped as `RpcException(FailedPrecondition, \"Can't access cart storage…\")`, and every `EmptyCart` RPC (called by checkout at order finalization) hung — the frontend surfaced HTTP 504 timeouts on `POST /api/checkout` and `DELETE /api/cart`.", + "mechanism": "The flag is read in the cart service at [`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83). When `cartFailure` is enabled, [`CartService.EmptyCart`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L85) routes to `_badCartStore` instead of the normal cart store.\n\nThe failure chain:\n\n1. **`_badCartStore`** is a `ValkeyCartStore` instantiated with the address `\"badhost:1234\"` — an unreachable Redis/Valkey host ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60)).\n2. **[`ValkeyCartStore.EmptyCartAsync`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)** calls [`EnsureRedisConnected`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L74), which blocks in `StackExchange.Redis ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds while DNS resolution / TCP connect to `badhost:1234` fails repeatedly.\n3. After the retries exhaust, [`ValkeyCartStore.cs#L98`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L98) logs `_logger.LogError(\"Wasn't able to connect to redis\")` and [`L101`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L101) throws `ApplicationException(\"Wasn't able to connect to redis\")`.\n4. The catch block at [`ValkeyCartStore.cs#L203`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L203) rewraps it as:\n ```\n RpcException(Status(StatusCode.FailedPrecondition, \"Can't access cart storage. \"))\n ```\n5. [`CartService.cs#L93-L96`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L93-L96) — the catch block records the error to OTLP and re-throws to the gRPC caller (checkout):\n ```csharp\n Activity.Current?.AddException(ex); // adds an exception event to the trace span\n Activity.Current?.SetStatus(ActivityStatusCode.Error, ex.Message); // marks span as Error\n throw;\n ```\n6. Checkout's `PlaceOrder` invokes `cs.emptyUserCart` synchronously at [`checkout/main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) and discards the return value with `_ =`, so PlaceOrder blocks on this hung gRPC call for the full backoff duration. `frontend-proxy` cuts the upstream request at its fixed 15 s route timeout, returning HTTP 504 (`UT response_timeout`) to the load-generator client — even though the order has already been charged and shipped earlier in `PlaceOrder`.", + "symptoms": { + "metrics": [ + { + "metric_family": "container_cpu_utilization_ratio", + "signal_layer": "root_cause", + "defining_labels": { + "container_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "container_cpu_utilization_ratio{container_name=\"cart\"}", + "description": "Cart container instantaneous CPU utilization ratio roughly doubled from an average of ~0.3 to ~1.0+ (with peaks reaching 2-4x baseline). Same root cause as the CPU nanoseconds rate — the retry loop against badhost:1234 — but measured as a noisier point-in-time gauge rather than a smoothed 5m rate.", + "onset_utc": "2026-04-24 17:35:00 UTC", + "onset_offset_seconds": -6, + "onset_reasoning": "Pre-incident baseline averages roughly 0.2-0.5 with occasional spikes to ~0.6. At 17:35 (incident time), the value jumps to 2.20, far above baseline. While 17:33 shows 1.25, this appears to be an isolated pre-incident fluctuation followed by a return to 0.26 at 17:34. Starting at 17:35, repeated spikes above 2.0 (at 17:39, 17:42, 17:50, 17:55) establish a new elevated pattern, confirming 17:35 as the onset." + } + ] + }, + { + "metric_family": "dotnet_thread_pool_work_item_count", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "cart" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(dotnet_thread_pool_work_item_count_total{service_name=\"cart\"}[5m])", + "description": "Rate of .NET thread pool work items processed in the cart service. Increases from ~14/s to ~23/s as additional work items are scheduled for connection retry callbacks and exception handling.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident baseline ranges ~11.8-15.4 (avg ~14.1). At 17:36, immediately after the incident time, the value jumps to 16.4458, clearly above the prior range, and continues rising steadily to ~23 by 17:55. This is the first timestamp after the incident where the metric breaks above baseline." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "9", + "rpc_method": "EmptyCart", + "rpc_service": "oteldemo.CartService", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_grpc_status_code=\"9\",rpc_method=\"EmptyCart\",rpc_service=\"oteldemo.CartService\"}[5m])", + "description": "Rate of gRPC FailedPrecondition (status 9) errors on checkout→cart EmptyCart calls. New series appeared ~4 min after cartFailure was enabled, caused by _badCartStore failing to connect to badhost:1234.", + "onset_utc": "2026-04-24 17:39:00 UTC", + "onset_offset_seconds": 233, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period and remains 0 until 17:39:00 UTC, when it first rises to ~0.00417. This is the first non-zero value after the incident at 17:35:06 UTC, representing the clear onset of the spike approximately 4 minutes after the incident injection." + } + ] + }, + { + "metric_family": "kafka_consumer_bytes_consumed_rate", + "signal_layer": "symptom", + "defining_labels": { + "topic": "orders" + }, + "variants": [ + { + "type": "collapsed", + "query": "kafka_consumer_bytes_consumed_rate{topic=\"orders\"}", + "description": "Rate of bytes consumed by the fraud-detection consumer from the Kafka 'orders' topic. Dropped ~65% (from ~8.9 to ~3.1 bytes/sec) with identical timing and cause as the records consumed rate — fewer order messages means fewer bytes read from the topic.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "Pre-incident, the metric oscillates with values regularly reaching 10-18 and only occasional single zeros. At 17:36 there is a final burst (23.39), then from 17:37 onward the signal collapses into consecutive zeros and only occasional small values (4-7 range), never recovering the pre-incident active pattern. 17:36 is the last timestamp showing vigorous pre-incident activity, aligning with the incident at 17:35:06." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "cartFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"cartFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impressions for cartFailure with variant 'on'. New series appeared when the flag was flipped, confirming flagd started serving cartFailure=true to the cart service.", + "onset_utc": "2026-04-24 17:36:00 UTC", + "onset_offset_seconds": 53, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. At 17:36 UTC (one minute after the incident time), the rate jumps to ~0.00417, marking the first non-zero value and the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 504", + "description": "Between 17:40:35.522 and 17:44:30.134 UTC (~5.5 min to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 6 POST /api/checkout requests from the load-generator returned HTTP 504 with Envoy response flag 'UT' (upstream request timeout) and a total duration of ~15000 ms each.", + "cause": "Downstream symptom of cartFailure. CheckoutService.PlaceOrder calls cart's EmptyCart RPC as its final step; with cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:83-85) routes to _badCartStore (a ValkeyCartStore constructed against 'badhost:1234' in src/cart/src/Program.cs:60), which blocks in ConnectionMultiplexer.Connect retry/backoff for hundreds of seconds. The checkout PlaceOrder span hangs on this call, and frontend-proxy cuts the upstream request at its fixed 15 s timeout, returning 504 UT response_timeout to the caller.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "[2026-04-24T17:40:35.522Z] \"POST /api/checkout HTTP/1.1\" 504 UT response_timeout - \"-\" 386 24 14999 - \"-\" \"python-requests/2.32.5\" \"f6bdcccd-b1a5-96ab-b164-d95975778d2a\" \"frontend-proxy:8080\" \"172.18.0.27:8080\" frontend 172.18.0.29:36634 172.18.0.29:8080 172.18.0.28:42900 - -", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "url.full": "http://frontend-proxy:8080/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "destination.address": "172.18.0.27", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "POeUwJ0Br_RFnSwRgfSX", + "@timestamp": "17:40:35.522" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "c-eVwJ0Br_RFnSwR1PcA", + "@timestamp": "17:42:02.062" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "LOeWwJ0Br_RFnSwRavkC", + "@timestamp": "17:42:40.393" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OeeWwJ0Br_RFnSwRcPlU", + "@timestamp": "17:42:42.847" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOeXwJ0Br_RFnSwRT_sB", + "@timestamp": "17:43:38.937" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-OeYwJ0Br_RFnSwRFv1-", + "@timestamp": "17:44:30.134" + } + ] + }, + { + "name": "cart: Wasn't able to connect to redis (ERROR)", + "description": "Between 17:37:35.797 and 17:44:25.690 UTC the cart service emitted 3 severity-Error logs 'Wasn't able to connect to redis' from cart.cartstore.ValkeyCartStore.", + "cause": "Direct effect of the cartFailure feature flag. When cartFailure=on, CartService.EmptyCart (src/cart/src/services/CartService.cs:85) calls _badCartStore.EmptyCartAsync, whose ValkeyCartStore is wired to the unreachable host 'badhost:1234' at src/cart/src/Program.cs:60. ValkeyCartStore.EnsureRedisConnected logs _logger.LogError(\"Wasn't able to connect to redis\") at src/cart/src/cartstore/ValkeyCartStore.cs:98 and then throws ApplicationException at line 101. The log is only emitted on this failing path — it is not produced during normal operation.", + "source": "cart service (.NET, cart.cartstore.ValkeyCartStore)", + "representative_attributes": { + "body": "Wasn't able to connect to redis", + "severity.text": "Error", + "severity.number": "17", + "instrumentationScope.name": "cart.cartstore.ValkeyCartStore", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kueRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9eeVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.657" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EOeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.690" + } + ] + }, + { + "name": "cart: gRPC FailedPrecondition — Can't access cart storage (INFO)", + "description": "Between 17:37:35.797 and 17:44:25.691 UTC (3 entries), Grpc.AspNetCore.Server.ServerCallHandler auto-logged the thrown RpcException as 'Error status code {StatusCode} with detail {Detail} raised.' with StatusCode=FailedPrecondition and a Detail field whose stack trace points precisely at ValkeyCartStore.EnsureRedisConnected (line 101) → ValkeyCartStore.EmptyCartAsync (line 194). Note severity is Information (9) despite being a server-side gRPC error — the ASP.NET Core gRPC handler logs these at Info by default. The first entry fires 1 ms after the corresponding ValkeyCartStore Error above, sharing its traceId and spanId.", + "cause": "Direct effect of cartFailure. ValkeyCartStore.EmptyCartAsync (src/cart/src/cartstore/ValkeyCartStore.cs:194) catches the ApplicationException from EnsureRedisConnected and rethrows it as RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\")) at line 203. The ASP.NET Core gRPC middleware (Grpc.AspNetCore.Server.ServerCallHandler) then structurally logs the resulting status+detail. The stack trace targets EmptyCartAsync specifically — not AddItemAsync or GetCartAsync — which is consistent with the CartService.EmptyCart branch being the only one wired to _badCartStore in CartService.cs:85.", + "source": "cart service (.NET, Grpc.AspNetCore.Server.ServerCallHandler)", + "representative_attributes": { + "body": "Error status code '{StatusCode}' with detail '{Detail}' raised.", + "severity.text": "Information", + "severity.number": "9", + "StatusCode": "FailedPrecondition", + "Detail": "Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194", + "instrumentationScope.name": "Grpc.AspNetCore.Server.ServerCallHandler", + "traceId": "fd443f414b372b4648d20fbb8159b043", + "spanId": "b089f6c296fba19a", + "resource.service.name": "cart", + "resource.service.namespace": "opentelemetry-demo", + "resource.service.version": "2.2.0", + "resource.telemetry.sdk.language": "dotnet" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "k-eRwJ0Br_RFnSwRkezM", + "@timestamp": "17:37:35.797" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ueVwJ0Br_RFnSwR_vfz", + "@timestamp": "17:42:25.659" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "EeeXwJ0Br_RFnSwR1_2E", + "@timestamp": "17:44:25.691" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page hangs for ~15 seconds and then fails — the user remains on the cart page and never reaches the order confirmation. The order is actually processed in the backend (payment is charged and items are shipped), but the user sees no confirmation and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while cartFailure is enabled.", + "source_file": "src/checkout/main.go", + "source_line": 353, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: after payment and shipping complete, [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353) calls `cs.emptyUserCart(ctx, req.UserId)` which invokes CartService.EmptyCart via gRPC. The return value (error) is discarded with `_ =`, but the call itself blocks synchronously.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. PlaceOrder succeeds through payment and shipping, then calls `cs.emptyUserCart` at [`main.go#L353`](../../opentelemetry-demo/src/checkout/main.go#L353). This invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)), which evaluates the `cartFailure` flag and routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), constructed with `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff for hundreds of seconds against the unreachable host. The frontend-proxy Envoy default route timeout (15 s) fires first, returning HTTP 504 with response flag `UT` (upstream request timeout). In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_timeout" + }, + { + "description": "Clicking \"Empty Cart\" on the cart page hangs for ~15 seconds and then fails — items remain in the cart.", + "route": "DELETE /api/cart", + "deterministic": true, + "trigger_condition": "User clicks \"Empty Cart\" on the cart page while cartFailure is enabled.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 45, + "calling_service": "frontend", + "call_pattern": "Single direct call: [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)` → gRPC `client.emptyCart` ([`Cart.gateway.ts#L23`](../../opentelemetry-demo/src/frontend/gateways/rpc/Cart.gateway.ts#L23)).", + "cause": "The DELETE handler in [`cart.ts#L45`](../../opentelemetry-demo/src/frontend/pages/api/cart.ts#L45) calls `CartGateway.emptyCart(userId)`, which invokes `CartService.EmptyCart` ([`CartService.cs#L83`](../../opentelemetry-demo/src/cart/src/services/CartService.cs#L83)). When cartFailure is on, the call routes to `_badCartStore` ([`Program.cs#L60`](../../opentelemetry-demo/src/cart/src/Program.cs#L60), `\"badhost:1234\"`). `ValkeyCartStore.EmptyCartAsync` ([`ValkeyCartStore.cs#L194`](../../opentelemetry-demo/src/cart/src/cartstore/ValkeyCartStore.cs#L194)) calls `EnsureRedisConnected`, which blocks in `ConnectionMultiplexer.Connect` retry/backoff against the unreachable host. The frontend-proxy Envoy 15 s default route timeout fires, returning HTTP 504 UT. The `emptyCartMutation` in [`Cart.provider.tsx#L52`](../../opentelemetry-demo/src/frontend/providers/Cart.provider.tsx#L52) rejects, but React Query absorbs the error — the cart items remain and the user stays on the cart page.", + "symptom_type": "http_timeout" + } + ], + "traces": [ + { + "name": "Checkout EmptyCart Cascade", + "description": "Between 17:35:40 and 17:44:29 UTC (34 s to ~9.4 min after cartFailure was flipped on at 17:35:06 UTC), 7 load-generator checkout traces failed. The root `load-generator:user_checkout_single|multi` span issues a POST through the frontend-proxy, which times out after exactly 15.0 s with HTTP 504. The underlying `cart:POST /oteldemo.CartService/EmptyCart` span hangs for 110–446 s in a `ConnectionMultiplexer.Connect` retry loop against the bogus host `badhost:1234`, then terminates with gRPC `FailedPrecondition` — 'Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis'. Because EmptyCart is the last step of `CheckoutService.PlaceOrder`, the `charged` and `shipped` span events fire before the failure: the customer is charged and the order is booked for shipping even though they see a 504.", + "cause": "Direct effect of the cartFailure feature flag. `CartService.EmptyCart` (`src/cart/src/services/CartService.cs:83-85`) evaluates `cartFailure`; when `on`, it routes the call to `_badCartStore`, an extra `ValkeyCartStore` instance constructed in `src/cart/src/Program.cs:60` with the unreachable connection string `badhost:1234`. `ValkeyCartStore.EmptyCartAsync` calls `EnsureRedisConnected` → `ConnectionMultiplexer.Connect`, which retries with exponential backoff for hundreds of seconds before throwing `ApplicationException(\"Wasn't able to connect to redis\")` at `ValkeyCartStore.cs:101`; the catch block at `ValkeyCartStore.cs:203` rewraps it as `RpcException(Status(FailedPrecondition, \"Can't access cart storage. {ex}\"))`. Because `checkout/main.go:353` calls `emptyUserCart` synchronously and discards the return value with `_ =`, the PlaceOrder RPC blocks on this hung call for the full backoff duration; `frontend-proxy` cuts the upstream request at its fixed 15 s timeout and the client receives HTTP 504.", + "call_chain": "cart:POST /oteldemo.CartService/EmptyCart → checkout:oteldemo.CartService/EmptyCart → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST → load-generator:user_checkout_single|user_checkout_multi", + "smoking_gun": [ + "`cart:POST /oteldemo.CartService/EmptyCart` span log `feature_flag.evaluation` with `feature_flag.key=cartFailure`, `feature_flag.provider.name=flagd Provider`, `feature_flag.result.reason=static`, `feature_flag.result.value=True`, `feature_flag.result.variant=on` — definitively proves the flag routed this call into `_badCartStore`.", + "`cart:POST /oteldemo.CartService/EmptyCart` span `otel.status_code=ERROR` with `otel.status_description=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. System.ApplicationException: Wasn't able to connect to redis\\n at cart.cartstore.ValkeyCartStore.EnsureRedisConnected() in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 101\\n at cart.cartstore.ValkeyCartStore.EmptyCartAsync(String userId) in /usr/src/app/src/cartstore/ValkeyCartStore.cs:line 194\")`.", + "`cart:POST /oteldemo.CartService/EmptyCart` exception event with `exception.type=Grpc.Core.RpcException`, `exception.message=Status(StatusCode=\"FailedPrecondition\", Detail=\"Can't access cart storage. ... Wasn't able to connect to redis\")`, and `exception.stacktrace` through `ValkeyCartStore.EmptyCartAsync:line 203` and `CartService.EmptyCart:line 85`.", + "`checkout:oteldemo.CartService/EmptyCart` and `cart:POST /oteldemo.CartService/EmptyCart` span durations between 110 s and 446 s across the 7 traces (well beyond normal Redis latency), which is consistent with `StackExchange.Redis ConnectionMultiplexer.Connect` exponential-backoff retries against `badhost:1234` rather than a normal transient network error.", + "`frontend-proxy:router frontend egress` error span with `error=true`, `canceled=true`, `http.status_code=0`, `response_flags=-`, and `duration≈15.00 s` — Envoy upstream timeout fired and canceled the request to the backend, while `load-generator:POST` records the resulting `http.status_code=504` and `otel.status_code=ERROR` returned to the client.", + "`checkout:oteldemo.CheckoutService/PlaceOrder` span event sequence observed *before* the EmptyCart failure: `prepared` → `feature_flag.evaluation paymentUnreachable=off` → `charged` (carrying `app.payment.transaction.id`) → `shipped` (carrying `app.shipping.tracking.id`) → `feature_flag.evaluation kafkaQueueProblems=off`. The order is fully charged and shipped *before* EmptyCart is invoked, confirming that the 504 surfaces only at the final cart-cleanup step." + ], + "trace_documents": [ + { + "traceID": "2d1bd9dbff5114ad0ce60327cf5c0b8f", + "@timestamp": "17:44:29", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "445.7", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "284be2d298860814da06501867dbc553", + "@timestamp": "17:43:38", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "374.3", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "198d4e85ea46d0bd16e8f7bb04a007df", + "@timestamp": "17:42:42", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "325.8", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "c45882e1fb7c6192bd271073f451496c", + "@timestamp": "17:42:40", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "227.2", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "281746526eb53bc8bfb9473e09be01a6", + "@timestamp": "17:42:02", + "user_action": "user_checkout_single", + "cart_empty_duration_seconds": "143.6", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "434b700dd1134a93a98d3c1a0dbf7a4e", + "@timestamp": "17:40:35", + "user_action": "user_checkout_multi", + "cart_empty_duration_seconds": "110.0", + "frontend_proxy_http_status": "504" + }, + { + "traceID": "fd443f414b372b4648d20fbb8159b043", + "@timestamp": "17:35:40", + "cart_empty_duration_seconds": "115.0" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-10%.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-10%.json new file mode 100644 index 0000000000000000000000000000000000000000..473eec01e3350ad3de3b95832beab09a0ee85079 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-10%.json @@ -0,0 +1,198 @@ +{ + "incident_time": "2026-04-24T17:50:09.830911+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 10% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~10% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.1` (variant `10%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 10% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the payment service's Charge RPC. This series was absent before the incident and appeared at 17:55 UTC — the paymentFailure flag causes charge.js to throw 'Payment request failed' with 10% probability, creating new STATUS_CODE_ERROR spans.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout-to-payment gRPC client Charge calls returning UNKNOWN (status 2) appeared from zero because the payment service's charge function throws an unhandled Error when the paymentFailure flag triggers, which gRPC maps to status UNKNOWN", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "The metric is flat at 0 from the start through 17:54. At 17:55 it spikes to ~0.00417, which is the first non-zero value after the incident time (17:50:09). This marks the onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",target=\"/api/checkout\",status=\"500\"}[5m])", + "description": "Frontend checkout POST requests returning HTTP 500 errors spiked because the paymentFailure flag causes the payment service to throw errors ~10% of the time, which propagates through checkout as gRPC INTERNAL and surfaces as HTTP 500 on the frontend", + "onset_utc": "2026-04-24 17:54:00 UTC", + "onset_offset_seconds": 230, + "onset_reasoning": "Pre-incident baseline shows sporadic ~0.004 values but is zero from 17:41-17:53. After the incident at 17:50, the metric begins rising at 17:54 (0.004) and continues climbing to 0.008 and 0.012 in subsequent minutes, clearly above the pre-incident sporadic noise pattern. This sustained increase marks the onset of the spike." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "10%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"10%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag with variant '10%', appearing from zero when the flag was activated — this is the direct flagd-side evidence of the feature flag being turned on", + "onset_utc": "2026-04-24 17:51:00 UTC", + "onset_offset_seconds": 50, + "onset_reasoning": "The metric was flat at 0 before the incident. At 17:51:00 UTC (one minute after the incident time), it spikes to ~0.00417, which is the first non-zero value and clearly the onset of the feature flag activation." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "propagation", + "defining_labels": { + "service_name": "checkout", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"checkout\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call counter for the checkout service's client-side call to PaymentService/Charge. This series was absent before the incident — it appears because the gRPC error from the payment service propagates to the checkout service's client span.", + "onset_utc": "2026-04-24 17:55:00 UTC", + "onset_offset_seconds": 290, + "onset_reasoning": "Baseline is 0 throughout the pre-incident period. After the incident at 17:50:09, the first non-zero value appears at 17:55:00 (~0.00417), marking the onset of the error rate spike for PaymentService/Charge calls." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 10% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 10%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "kuigwJ0Br_RFnSwRDhJp", + "@timestamp": "17:53:27.788" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "buizwJ0Br_RFnSwR80qd", + "@timestamp": "18:15:11.623" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 73–157ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 10%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3uigwJ0Br_RFnSwRIRJr", + "@timestamp": "17:53:27.862" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "C-i0wJ0Br_RFnSwRCUu9", + "@timestamp": "18:15:11.781" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~10% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 10% probability (`Math.random() < 0.1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 17:53:27 and 18:15:11 UTC, 2 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 10% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 10% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.1), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "5dfdc18a2a9381d9d1f694c9a0739a49", + "@timestamp": "17:53:27", + "user_action": "user_checkout_multi" + }, + { + "traceID": "f88b54398526e3e4076a6ae0fd73cac6", + "@timestamp": "18:15:11", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-100%.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-100%.json new file mode 100644 index 0000000000000000000000000000000000000000..247c7dadd0fa1a561701858d0daf56de76b952cb --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-100%.json @@ -0,0 +1,412 @@ +{ + "incident_time": "2026-04-24T18:50:26.427575+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 100% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on every call; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `1` (variant `100%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 100% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived call count for successful payment charges (STATUS_CODE_UNSET) flatlined to zero after the paymentFailure flag caused 100% of charges to fail, eliminating all successful payment spans", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows an active, oscillating pattern with values ranging ~0.004–0.017 throughout the pre-incident period. At 18:50:00 the last non-zero value (0.00416668) is recorded, and from 18:51:00 onward the signal drops to exactly 0 and never recovers. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration observation count for successful payment charges flatlined to zero, matching the calls_total collapse since no successful charge spans are emitted", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows active oscillation in the pre-incident period with values ranging ~0.004-0.017. At 18:50:00 the last non-zero value (0.00416668) is recorded, coinciding with the incident time. From 18:51:00 onward the signal drops to exactly 0 and never recovers. The last active timestamp is 18:50:00." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration for successful payment charges flatlined to zero, as no successful charge spans contribute duration samples", + "onset_utc": "2026-04-24 18:50:00 UTC", + "onset_offset_seconds": -26, + "onset_reasoning": "The metric shows typical oscillating activity in the pre-incident period with values ranging roughly 0.003-0.015. At 18:50:00 the last non-zero value (0.00332103) is recorded, and starting at 18:51:00 the signal drops to zero permanently. This aligns precisely with the incident time at 18:50:26, so 18:50:00 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + }, + { + "metric_family": "aspnetcore_routing_match_attempts", + "signal_layer": "propagation", + "defining_labels": { + "http_route": "/oteldemo.CartService/EmptyCart", + "service_name": "cart" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(aspnetcore_routing_match_attempts_total{service_name=\"cart\", http_route=\"/oteldemo.CartService/EmptyCart\"}[5m])", + "description": "ASP.NET Core routing match attempts for the cart service's EmptyCart endpoint flatlined to zero. When checkout fails due to payment errors, the checkout service (main.go) never reaches the cart-emptying step, so EmptyCart is never called. The raw counter froze at 10408 at incident onset while AddItem continued increasing normally.", + "onset_utc": "2026-04-24 18:49:00 UTC", + "onset_offset_seconds": -86, + "onset_reasoning": "The metric shows active oscillation (0.004–0.017 req/s) through 18:49, then drops to zero at 18:50 and never recovers. The last non-trivial value is at 18:49:00, aligning closely with the incident time of 18:50:26." + } + ] + }, + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.CheckoutService/PlaceOrder", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"frontend\",span_name=\"oteldemo.CheckoutService/PlaceOrder\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived error call count for frontend's outgoing CheckoutService/PlaceOrder call spiked ~4x as payment failures propagate through checkout to the frontend", + "onset_utc": "2026-04-24 18:54:00 UTC", + "onset_offset_seconds": 213, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 0.004-0.017. After the incident at 18:50, values remain at baseline through 18:53 (~0.0125). At 18:54 the rate jumps to 0.025, approximately double the typical baseline, and sustains elevated levels (0.025-0.029) for several minutes, representing a clear spike above the pre-incident range." + } + ] + }, + { + "metric_family": "kafka_logs_flush_time_99p_milliseconds", + "signal_layer": "meta", + "defining_labels": {}, + "variants": [ + { + "type": "spiked", + "query": "kafka_logs_flush_time_99p_milliseconds", + "description": "Kafka broker 99th-percentile log flush latency spiked from ~27ms to ~274ms (peak) around 19:01–19:07 UTC, reflecting increased I/O pressure on the Kafka broker as the system processed checkout failure responses and retries.", + "onset_utc": "2026-04-24 18:51:00 UTC", + "onset_offset_seconds": 33, + "onset_reasoning": "Pre-incident baseline fluctuates roughly between 20-31 ms. At 18:51, immediately after the incident marker, the value jumps to 32.87 and continues climbing through 35, 45, 52, and then dramatically to 179-274 ms. The 18:51 reading is the first post-incident point that breaks above the prior baseline range and marks the beginning of a sustained upward trend." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a deterministic failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "cujUwJ0Br_RFnSwRy6dR", + "@timestamp": "18:51:04.049" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tujVwJ0Br_RFnSwRPKii", + "@timestamp": "18:51:33.190" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CujVwJ0Br_RFnSwRqqqg", + "@timestamp": "18:52:00.600" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "wujVwJ0Br_RFnSwRzarD", + "@timestamp": "18:52:10.264" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "b-jVwJ0Br_RFnSwR6ash", + "@timestamp": "18:52:16.994" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "p-jWwJ0Br_RFnSwRM6xW", + "@timestamp": "18:52:36.141" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "lejXwJ0Br_RFnSwRsrAn", + "@timestamp": "18:54:14.114" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujYwJ0Br_RFnSwRNrKV", + "@timestamp": "18:54:47.514" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KejZwJ0Br_RFnSwRRLWa", + "@timestamp": "18:55:57.243" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "VejZwJ0Br_RFnSwR5Ldq", + "@timestamp": "18:56:37.676" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "tOjawJ0Br_RFnSwRlLmP", + "@timestamp": "18:57:23.007" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OujbwJ0Br_RFnSwRCbvV", + "@timestamp": "18:57:53.169" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "_ujbwJ0Br_RFnSwRQLss", + "@timestamp": "18:58:06.527" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "mujbwJ0Br_RFnSwRV7zw", + "@timestamp": "18:58:13.071" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jOjbwJ0Br_RFnSwR7L4j", + "@timestamp": "18:58:50.516" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOjcwJ0Br_RFnSwRYcBn", + "@timestamp": "18:59:20.812" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 29–110ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') on every call (Math.random() is always < 1.0). The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "3OjUwJ0Br_RFnSwR3qci", + "@timestamp": "18:51:04.090" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-jVwJ0Br_RFnSwRT6ms", + "@timestamp": "18:51:33.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hejVwJ0Br_RFnSwRvapK", + "@timestamp": "18:52:00.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "D-jVwJ0Br_RFnSwR4Kur", + "@timestamp": "18:52:10.320" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "KOjVwJ0Br_RFnSwR_Kw4", + "@timestamp": "18:52:17.104" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9ejWwJ0Br_RFnSwRRqy7", + "@timestamp": "18:52:36.170" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjXwJ0Br_RFnSwRxbDM", + "@timestamp": "18:54:14.163" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fOjYwJ0Br_RFnSwRRrL6", + "@timestamp": "18:54:47.552" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "hujZwJ0Br_RFnSwRWLWm", + "@timestamp": "18:55:57.296" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "4ujZwJ0Br_RFnSwR9bcc", + "@timestamp": "18:56:37.734" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-jawJ0Br_RFnSwRqboX", + "@timestamp": "18:57:23.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "nOjbwJ0Br_RFnSwRHruN", + "@timestamp": "18:57:53.236" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "WOjbwJ0Br_RFnSwRUbyW", + "@timestamp": "18:58:06.575" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "BejbwJ0Br_RFnSwRbb0n", + "@timestamp": "18:58:13.146" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "GejbwJ0Br_RFnSwR_b_z", + "@timestamp": "18:58:50.593" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ejcwJ0Br_RFnSwRc8Bm", + "@timestamp": "18:59:20.905" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page returns an error every time — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge on every request (`Math.random() < 1` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33) is always true).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); since `Math.random() < 1` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)) is always true, it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:51:04 and 18:59:20 UTC, 16 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a deterministic failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 100% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and on every call (Math.random() is always < 1.0) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "2971e8d3ec343f4c554c138793e7e21d", + "@timestamp": "18:51:04", + "user_action": "user_checkout_single" + }, + { + "traceID": "59588e4605b062a1ec18bcb9ec7b0724", + "@timestamp": "18:51:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "192ba953c5ee6f54a879cbf1555a4be5", + "@timestamp": "18:52:00", + "user_action": "user_checkout_single" + }, + { + "traceID": "b789a56dbdb15fe48a07270e4de76549", + "@timestamp": "18:52:10", + "user_action": "user_checkout_single" + }, + { + "traceID": "3971fdaf0d54cb151bc2aa1fba5d9e46", + "@timestamp": "18:52:13", + "user_action": "user_checkout_multi" + }, + { + "traceID": "8d2a0c6d4d38c81606a54cf4cd7fadf3", + "@timestamp": "18:52:33", + "user_action": "user_checkout_single" + }, + { + "traceID": "0ccae3f20d840c4d2e473f4588ae2e72", + "@timestamp": "18:54:14", + "user_action": "user_checkout_single" + }, + { + "traceID": "33f03353bb2a6e5c4368e8f941ec02db", + "@timestamp": "18:54:47", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e96c7fb3467dd9b9c4580595f613cc4c", + "@timestamp": "18:55:57", + "user_action": "user_checkout_single" + }, + { + "traceID": "0f4c629ba9490c02c2ec1a5118fe3e4d", + "@timestamp": "18:56:37", + "user_action": "user_checkout_multi" + }, + { + "traceID": "d442ea033323084645c548d352633071", + "@timestamp": "18:57:22", + "user_action": "user_checkout_single" + }, + { + "traceID": "8334be013b2a9fba3723c4ac19398858", + "@timestamp": "18:57:53", + "user_action": "user_checkout_multi" + }, + { + "traceID": "63ac33f4fbd83c9f760c02a6deed1c9a", + "@timestamp": "18:58:06", + "user_action": "user_checkout_single" + }, + { + "traceID": "ea6454df13a9cefe488c27ed7db09dad", + "@timestamp": "18:58:12", + "user_action": "user_checkout_multi" + }, + { + "traceID": "67bdcf41eac68463f1f81bd75932bcdf", + "@timestamp": "18:58:50", + "user_action": "user_checkout_multi" + }, + { + "traceID": "fb5419d459e0e8747b959d1d1af10daa", + "@timestamp": "18:59:20", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-50%.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-50%.json new file mode 100644 index 0000000000000000000000000000000000000000..9116f2918e13ac9bdb1e6d587c1a60ea0c5d4d60 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-paymentFailure-50%.json @@ -0,0 +1,333 @@ +{ + "incident_time": "2026-04-24T18:20:18.481618+00:00", + "feature_flag": "paymentFailure", + "description": "A feature flag set to 50% in the payment service's `charge.js` caused the `charge` function to throw `Error(\"Payment request failed. Invalid token. …\")` on ~50% of calls; the checkout service's `chargeCard` turned the gRPC error into `\"could not charge the card\"`, `PlaceOrder` returned gRPC `Internal`, and the frontend proxied it as HTTP 500 on `POST /api/checkout`.", + "mechanism": "The flag is read in [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29): the payment service's `charge` function evaluates `getNumberValue(\"paymentFailure\", 0)`, which returns `0.5` (variant `50%`). When the value is > 0, it generates a random number and fails the request if `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), giving a 50% failure rate.\n\nOn failure (lines 34-37), the span is annotated with `app.loyalty.level=gold` and the function throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')`. The error propagates through the gRPC payment service to the checkout service's `chargeCard` at [`main.go#L552-L556`](../../opentelemetry-demo/src/checkout/main.go#L552), which returns `\"could not charge the card: ...\"`, and the checkout handler returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335), failing the order.", + "symptoms": { + "metrics": [ + { + "metric_family": "traces_span_metrics_calls", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "payment", + "span_name": "oteldemo.PaymentService/Charge", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(traces_span_metrics_calls_total{service_name=\"payment\",span_name=\"oteldemo.PaymentService/Charge\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived call counter for payment service's PaymentService/Charge RPC with ERROR status. The paymentFailure flag causes charge.js to throw 'Payment request failed' ~50% of the time, producing error spans that were absent before the incident.", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows sporadic low-level error rates (~0.004). After the incident at 18:20, there's a brief dip to 0, then at 18:25 the rate jumps to ~0.0083 and continues climbing to ~0.0167, roughly 2-4x the pre-incident sporadic values. This sustained elevated pattern starting at 18:25 represents the clear onset of the spike." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "2", + "rpc_method": "Charge", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"Charge\",rpc_grpc_status_code=\"2\"}[5m])", + "description": "Checkout service's gRPC Charge calls to the payment service returning UNKNOWN (code 2) errors spiked ~1192% as payment failures are thrown as unhandled JS errors translated to gRPC UNKNOWN", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline shows intermittent values around 0.004 with zeros. After the incident at 18:20, the metric is zero until 18:25:00 when it jumps to 0.00833326 (~2x baseline), then continues rising to 0.0167 (~4x baseline). This is the first clear spike above the pre-incident pattern." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "POST", + "status": "500", + "target": "/api/checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{method=\"POST\",status=\"500\",target=\"/api/checkout\"}[5m])", + "description": "Frontend POST /api/checkout requests returning HTTP 500 spiked ~334% as payment failures propagate through checkout to the frontend as HTTP 500 errors", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "Pre-incident, the metric shows sporadic low-level 500 errors that drop to 0 at the incident time (18:20). After the incident, the metric begins rising at 18:24 with 0.00416651, then climbs sharply to sustained higher values (peaking around 0.0208) that exceed the pre-incident sporadic pattern. This post-incident sustained elevation starting at 18:24 represents the clear onset of the spike caused by the incident." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "paymentFailure", + "feature_flag_result_variant": "50%" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"paymentFailure\",feature_flag_result_variant=\"50%\"}[5m])", + "description": "flagd recorded impressions for the paymentFailure flag evaluated at the 50% variant, appearing from zero after the flag was activated", + "onset_utc": "2026-04-24 18:24:00 UTC", + "onset_offset_seconds": 221, + "onset_reasoning": "The metric is flat at 0 from 18:00 through 18:23. At 18:24 it spikes to 0.00416667, which is the first non-zero value after the incident time (18:20). This is the onset of the spike." + } + ] + }, + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "PlaceOrder", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"checkout\",rpc_method=\"PlaceOrder\",rpc_grpc_status_code=\"13\"}[5m])", + "description": "Checkout PlaceOrder gRPC server calls returning INTERNAL (code 13) spiked ~322% because payment charge failures cascade through PlaceOrder as codes.Internal", + "onset_utc": "2026-04-24 18:25:00 UTC", + "onset_offset_seconds": 281, + "onset_reasoning": "Pre-incident baseline ranges 0-0.0125. After the incident at 18:20, values are zero until 18:24 (0.004), then at 18:25 the value jumps to 0.0125 and continues rising to 0.0167-0.0208, clearly exceeding the pre-incident maximum. 18:25 marks the start of the sustained upward trajectory into the spiked regime." + } + ] + } + ], + "logs": [ + { + "name": "POST /api/checkout → 500", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 Envoy access log entries show POST /api/checkout returning HTTP 500 with a 21-byte error response body, at a 50% random failure rate set by the paymentFailure flag.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') with probability 50%. The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" ... 21 ...", + "event.name": "proxy.access", + "upstream.cluster": "frontend", + "url.path": "/api/checkout", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "B-i7wJ0Br_RFnSwRYV-G", + "@timestamp": "18:23:18.300" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "A-i7wJ0Br_RFnSwRoGAG", + "@timestamp": "18:23:34.601" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5-i8wJ0Br_RFnSwRtWJx", + "@timestamp": "18:24:45.325" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2-i9wJ0Br_RFnSwRUmSY", + "@timestamp": "18:25:25.561" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ui_wJ0Br_RFnSwRBGk-", + "@timestamp": "18:27:16.181" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "fui_wJ0Br_RFnSwRN2oF", + "@timestamp": "18:27:30.093" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-jMwJ0Br_RFnSwR85GE", + "@timestamp": "18:42:30.321" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "-ujOwJ0Br_RFnSwRdZXM", + "@timestamp": "18:44:08.608" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "qejPwJ0Br_RFnSwRNZjR", + "@timestamp": "18:44:57.492" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOjQwJ0Br_RFnSwRdpw5", + "@timestamp": "18:46:20.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "2ujRwJ0Br_RFnSwRh57B", + "@timestamp": "18:47:30.072" + } + ] + }, + { + "name": "payment: Payment request failed (WARN)", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 payment service warn-level logs record the charge rejection with full error stack trace. Each entry correlates 1:1 with a checkout 500, arriving 39–116ms after it.", + "cause": "Direct evidence of paymentFailure flag — charge.js:37 throws Error('Payment request failed. Invalid token. app.loyalty.level=gold') when Math.random() < 50%. The payment-logger (Pino) logs the error at warn severity before the gRPC callback returns it to the checkout service.", + "source": "payment service (Node.js)", + "representative_attributes": { + "body": "Payment request failed. Invalid token. app.loyalty.level=gold", + "severity.text": "warn", + "severity.number": "13", + "err.message": "Payment request failed. Invalid token. app.loyalty.level=gold", + "err.type": "Error", + "err.stack": "Error: Payment request failed. Invalid token. app.loyalty.level=gold\n at module.exports.charge (/usr/src/app/charge.js:37:13)\n at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n at async Object.chargeServiceHandler [as charge] (/usr/src/app/index.js:21:22)", + "instrumentationScope.name": "payment-logger", + "resource.service.name": "payment" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "nui7wJ0Br_RFnSwRdl9O", + "@timestamp": "18:23:18.417" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "f-i7wJ0Br_RFnSwRtWAI", + "@timestamp": "18:23:34.662" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "k-i8wJ0Br_RFnSwRymO5", + "@timestamp": "18:24:45.387" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "JOi9wJ0Br_RFnSwRZ2VB", + "@timestamp": "18:25:25.654" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "OOi_wJ0Br_RFnSwRFWqH", + "@timestamp": "18:27:16.238" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "5ui_wJ0Br_RFnSwRTGpv", + "@timestamp": "18:27:30.144" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IejNwJ0Br_RFnSwRCJIb", + "@timestamp": "18:42:30.360" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "w-jOwJ0Br_RFnSwRh5Ze", + "@timestamp": "18:44:08.655" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6OjPwJ0Br_RFnSwRR5gE", + "@timestamp": "18:44:57.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0OjQwJ0Br_RFnSwRi5zD", + "@timestamp": "18:46:20.196" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "P-jRwJ0Br_RFnSwRnZ-O", + "@timestamp": "18:47:30.115" + } + ] + } + ], + "frontend": [ + { + "description": "Clicking \"Place Order\" on the cart page intermittently returns an error (~50% of the time) — the user remains on the cart page and never reaches the order confirmation. No payment is charged, no items are shipped, and the cart is not emptied.", + "route": "POST /api/checkout", + "deterministic": false, + "trigger_condition": "User clicks \"Place Order\" on the cart page while paymentFailure is enabled. The payment service rejects the charge with 50% probability (`Math.random() < 0.5` in [`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)).", + "source_file": "src/checkout/main.go", + "source_line": 333, + "calling_service": "checkout", + "call_pattern": "Sequential call within PlaceOrder: [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333) calls `cs.chargeCard(ctx, total, req.CreditCard)`, which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The charge fails before shipping or cart cleanup.", + "cause": "The frontend API route [`checkout.ts#L18`](../../opentelemetry-demo/src/frontend/pages/api/checkout.ts#L18) calls `CheckoutGateway.placeOrder`, which invokes the checkout service's `PlaceOrder` gRPC. `PlaceOrder` calls `cs.chargeCard` at [`main.go#L333`](../../opentelemetry-demo/src/checkout/main.go#L333), which calls `paymentService.Charge()` at [`main.go#L552`](../../opentelemetry-demo/src/checkout/main.go#L552). The payment service evaluates the paymentFailure flag at [`charge.js#L29`](../../opentelemetry-demo/src/payment/charge.js#L29); when `Math.random() < 0.5` ([`charge.js#L33`](../../opentelemetry-demo/src/payment/charge.js#L33)), it throws `Error('Payment request failed. Invalid token. app.loyalty.level=gold')` at [`charge.js#L37`](../../opentelemetry-demo/src/payment/charge.js#L37). The error is caught in [`index.js#L24`](../../opentelemetry-demo/src/payment/index.js#L24) and returned via gRPC callback. `chargeCard` wraps it as `\"could not charge the card\"` ([`main.go#L556`](../../opentelemetry-demo/src/checkout/main.go#L556)), and `PlaceOrder` returns `codes.Internal` at [`main.go#L335`](../../opentelemetry-demo/src/checkout/main.go#L335). The frontend surfaces the gRPC error as HTTP 500. In `CartDetail.tsx`, the `await placeOrder(...)` at [`CartDetail.tsx#L38`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L38) rejects, so `push` to the confirmation page at [`CartDetail.tsx#L57`](../../opentelemetry-demo/src/frontend/components/Cart/CartDetail.tsx#L57) never executes.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Checkout Payment Failure Cascade", + "description": "Between 18:23:18 and 18:47:30 UTC, 11 traces show checkout failing due to the payment service rejecting charges with 'Payment request failed. Invalid token.' at a 50% random failure rate, cascading through the checkout path as HTTP 500.", + "cause": "Direct effect of paymentFailure flag set to 50% — payment service's charge function (src/payment/charge.js:29-38) evaluates the paymentFailure flag via OpenFeature.getNumberValue(), and with probability equal to the flag value (0.5), throws Error('Payment request failed. Invalid token. app.loyalty.level=gold'). The error propagates through checkout's chargeCard (src/checkout/main.go:552-556) as 'could not charge the card', then through PlaceOrder as gRPC INTERNAL, and the frontend proxies it as HTTP 500.", + "call_chain": "payment:charge → payment:oteldemo.PaymentService/Charge → checkout:oteldemo.PaymentService/Charge → checkout:oteldemo.CheckoutService/PlaceOrder → frontend:oteldemo.CheckoutService/PlaceOrder → frontend:executing api route (pages) /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "payment:oteldemo.PaymentService/Charge span exception.message: 'Payment request failed. Invalid token. app.loyalty.level=gold' (matches charge.js:37)", + "payment:charge span attribute: app.loyalty.level=gold (set at charge.js:34 only when paymentFailure flag triggers)" + ], + "trace_documents": [ + { + "traceID": "e185b10d8d9ac6e95cf95b6319b73d95", + "@timestamp": "18:23:18", + "user_action": "user_checkout_multi" + }, + { + "traceID": "e5cd2b4b2292bde45a1cf75f97f8feba", + "@timestamp": "18:23:34", + "user_action": "user_checkout_single" + }, + { + "traceID": "9993837832fef5a7fdc7145479865fda", + "@timestamp": "18:24:45", + "user_action": "user_checkout_multi" + }, + { + "traceID": "ec94ef333f5360576ab79cc8399321d1", + "@timestamp": "18:25:25", + "user_action": "user_checkout_single" + }, + { + "traceID": "76c1afbbdeb5ac374302d834b144cf58", + "@timestamp": "18:27:16", + "user_action": "user_checkout_single" + }, + { + "traceID": "370ab7c3cd8589eb4946626aad0492a6", + "@timestamp": "18:27:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "c8406bd14154290d88af9fccc4992ca4", + "@timestamp": "18:42:30", + "user_action": "user_checkout_single" + }, + { + "traceID": "585d341a675ef6319674baaccdf8aebb", + "@timestamp": "18:44:08", + "user_action": "user_checkout_multi" + }, + { + "traceID": "26a473539af7747bbe5c8c4a67a97947", + "@timestamp": "18:44:57", + "user_action": "user_checkout_multi" + }, + { + "traceID": "18aa7770cdf72edc205f10a8dcd6686f", + "@timestamp": "18:46:20", + "user_action": "user_checkout_multi" + }, + { + "traceID": "957aecd7b21bd55f1e36245b056e76b6", + "@timestamp": "18:47:30", + "user_action": "user_checkout_single" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-productCatalogFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-productCatalogFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..b6c39ad2bbea94901dfb3d53116687c6dc8f1b0e --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-productCatalogFailure-on.json @@ -0,0 +1,488 @@ +{ + "incident_time": "2026-04-24T17:04:56.642846+00:00", + "feature_flag": "productCatalogFailure", + "description": "A feature flag made the product-catalog `GetProduct` RPC return gRPC `Internal` whenever the requested SKU was `OLJCESPC7Z`; the frontend (product page, cart enrichment, recommendation enrichment) and the checkout service all call `GetProduct` unguarded, so the single-SKU failure cascaded into HTTP 500s on `/api/products/OLJCESPC7Z`, `/api/cart`, `/api/recommendations`, and `/api/checkout`.", + "mechanism": "The feature flag is checked in [`main.go#L485-L495`](../../opentelemetry-demo/src/product-catalog/main.go#L485-L495): `checkProductFailure` queries the OpenFeature/flagd provider for the `productCatalogFailure` flag, but only when the requested product ID is `OLJCESPC7Z`. For any other product ID, the function returns `false` immediately.\n\nWhen the flag is enabled and the product matches ([`main.go#L439-L444`](../../opentelemetry-demo/src/product-catalog/main.go#L439-L444)):\n\n1. The OpenTelemetry span is marked as an error with `span.SetStatus(otelcodes.Error, msg)` — this propagates to the tracing backend (Jaeger)\n2. A span event is added for additional trace detail via `span.AddEvent(msg)`\n3. A gRPC error with `codes.Internal` is returned via `status.Errorf`\n\nThe gRPC framework sends the `Internal` status back to the caller. Upstream services that call `GetProduct` for this product ID receive the error:\n\n- **Frontend** — calls `GetProduct` via [`ProductCatalog.gateway.ts#L17-L19`](../../opentelemetry-demo/src/frontend/gateways/rpc/ProductCatalog.gateway.ts#L17-L19) for product detail pages, cart operations, checkout, and recommendation enrichment. Since the frontend is instrumented with `otelgrpc`, the gRPC error appears in client-side spans.\n- **Checkout service** — calls `GetProduct` per cart item in [`main.go#L519`](../../opentelemetry-demo/src/checkout/main.go#L519). If product `OLJCESPC7Z` is in the cart, checkout fails with `\"failed to get product\"`.\n\nThe recommendation service is **not** directly affected — it calls `ListProducts` ([`recommendation_server.py#L95`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L95)), not `GetProduct`, so the per-product failure does not trigger. However, the `app_recommendations_counter` metric may still flatline because the frontend enriches recommendation IDs by calling `GetProduct` for each one ([`recommendations.ts#L21`](../../opentelemetry-demo/src/frontend/pages/api/recommendations.ts#L21)), and if `OLJCESPC7Z` is among the recommended products, the frontend request fails.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "gRPC server-side GetProduct calls returning INTERNAL error on product-catalog service, directly caused by the productCatalogFailure feature flag rejecting requests for product OLJCESPC7Z", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), which is the first timestamp after the incident where the metric clearly begins to spike above the zero baseline." + }, + { + "type": "spiked", + "query": "rate(rpc_server_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Cumulative server-side duration of failed GetProduct INTERNAL calls on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period through 17:05. At 17:06 it jumps to 0.00583, the first non-zero value, clearly marking the onset of the spike following the incident at 17:04:56." + } + ] + }, + { + "metric_family": "rpc_server_requests_per_rpc", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC count for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The baseline is consistently 0 from 16:44 through 17:05. The first non-zero value appears at 17:06 (0.00833333), immediately after the incident time, marking the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_server_requests_per_rpc_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"product-catalog\"}[5m])", + "description": "Server-side requests-per-RPC sum for GetProduct INTERNAL errors on product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00833333), which is the first clear rise above the baseline of 0, occurring ~1 minute after the incident injection at 17:04:56 UTC." + } + ] + }, + { + "metric_family": "rpc_client_duration_milliseconds", + "signal_layer": "propagation", + "defining_labels": { + "rpc_grpc_status_code": "13", + "rpc_method": "GetProduct", + "service_name": "checkout" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_count{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "gRPC client-side GetProduct calls returning INTERNAL error as seen by checkout service calling product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 for the entire pre-incident period. The first non-zero value appears at 17:06:00 UTC (~0.00417), approximately 1 minute after the incident time, representing the clear onset of the spike." + }, + { + "type": "spiked", + "query": "rate(rpc_client_duration_milliseconds_sum{rpc_method=\"GetProduct\",rpc_grpc_status_code=\"13\",service_name=\"checkout\"}[5m])", + "description": "Cumulative client-side duration of failed GetProduct INTERNAL calls from checkout to product-catalog", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "Pre-incident baseline is consistently 0. The first non-zero value after the incident time (17:04:56) appears at 17:06:00 with 0.00399278, marking the clear onset of the spike." + } + ] + }, + { + "metric_family": "app_frontend_requests", + "signal_layer": "symptom", + "defining_labels": { + "method": "GET", + "status": "500", + "target": "/api/products/OLJCESPC7Z" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(app_frontend_requests_total{status=\"500\",target=\"/api/products/OLJCESPC7Z\",method=\"GET\"}[5m])", + "description": "Frontend app-level counter for GET /api/products/OLJCESPC7Z returning HTTP 500, caused by GetProduct failure for the flagged product", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 from 16:44 through 17:05 (incident marker). At 17:06 it jumps to ~0.00417, the first non-zero value, clearly marking the start of the spike above the zero baseline." + } + ] + }, + { + "metric_family": "feature_flag_flagd_impression", + "signal_layer": "meta", + "defining_labels": { + "feature_flag_key": "productCatalogFailure", + "feature_flag_result_variant": "on" + }, + "variants": [ + { + "type": "spiked", + "query": "rate(feature_flag_flagd_impression_total{feature_flag_key=\"productCatalogFailure\",feature_flag_result_variant=\"on\"}[5m])", + "description": "flagd impression counter for productCatalogFailure flag with variant=on incremented at 17:06 UTC, confirming the flag was evaluated as enabled", + "onset_utc": "2026-04-24 17:06:00 UTC", + "onset_offset_seconds": 63, + "onset_reasoning": "The metric is flat at 0 throughout the pre-incident period. The first non-zero value appears at 17:06:00 UTC (0.00416667), which is 1 minute after the incident marker. This is the clear onset of the spike." + } + ] + } + ], + "logs": [ + { + "name": "GET /api/products/OLJCESPC7Z → 500", + "description": "Between 17:05:06 and 17:14:50 UTC, GET /api/products/OLJCESPC7Z was returning 500 errors.", + "cause": "Direct effect of productCatalogFailure flag — only product OLJCESPC7Z fails.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/products/OLJCESPC7Z HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 7 7 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/products/OLJCESPC7Z", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "KOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.131" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "I-d2wJ0Br_RFnSwRb5TG", + "@timestamp": "17:08:00.043" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "n-d3wJ0Br_RFnSwRDpZ1", + "@timestamp": "17:08:40.620" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "6ed3wJ0Br_RFnSwRvphO", + "@timestamp": "17:09:25.711" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "cud4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.363" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Oed4wJ0Br_RFnSwR85wJ", + "@timestamp": "17:10:44.616" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "IOd5wJ0Br_RFnSwRTp2D", + "@timestamp": "17:11:08.428" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "xed8wJ0Br_RFnSwRsabY", + "@timestamp": "17:14:50.652" + } + ] + }, + { + "name": "GET /api/recommendations → 500", + "description": "Between 17:06:25 and 17:13:48 UTC, GET /api/recommendations was returning 500 errors.", + "cause": "Cascading failure — the frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails. Various product IDs appear in the URL because the frontend fetches recommendations on different product pages.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"GET /api/recommendations?productIds={product_id} HTTP/1.1\" 500 - via_upstream - \"-\" 0 21 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/recommendations?productIds={product_id}", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "oOd1wJ0Br_RFnSwRAI5Z", + "@timestamp": "17:06:25.668" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "bOd2wJ0Br_RFnSwRM5Oh", + "@timestamp": "17:07:45.085" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "0ud2wJ0Br_RFnSwRUpPj", + "@timestamp": "17:07:53.138" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "s-d2wJ0Br_RFnSwRpJT4", + "@timestamp": "17:08:13.569" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "MOd2wJ0Br_RFnSwRyJUY", + "@timestamp": "17:08:22.286" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "7ed5wJ0Br_RFnSwRZJ1d", + "@timestamp": "17:11:14.185" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "ROd6wJ0Br_RFnSwRP6Ac", + "@timestamp": "17:12:09.535" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Q-d7wJ0Br_RFnSwRBKIW", + "@timestamp": "17:13:00.530" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Ved7wJ0Br_RFnSwRbaOW", + "@timestamp": "17:13:27.203" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "Xed7wJ0Br_RFnSwRrqRn", + "@timestamp": "17:13:43.318" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "jud7wJ0Br_RFnSwRvqQK", + "@timestamp": "17:13:48.062" + } + ] + }, + { + "name": "POST /api/checkout → 500", + "description": "Between 17:05:06 and 17:10:29 UTC, POST /api/checkout was returning 500 errors.", + "cause": "Cascading failure — the checkout service calls GetProduct for each cart item in prepOrderItems (checkout/main.go:519). When OLJCESPC7Z is in the cart, that call returns codes.Internal, causing PlaceOrder to fail with 'failed to get product #OLJCESPC7Z', which propagates back to the frontend as a 500.", + "source": "frontend-proxy Envoy access logs", + "representative_attributes": { + "body": "\"POST /api/checkout HTTP/1.1\" 500 - via_upstream - \"-\" 395 21 28 27 ...", + "severity": "", + "event.name": "proxy.access", + "url.path": "/api/checkout", + "upstream.cluster": "frontend", + "upstream.host": "172.18.0.27:8080", + "user_agent.original": "python-requests/2.32.5", + "resource.service.name": "frontend-proxy", + "resource.log_name": "otel_envoy_access_log" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "LOdzwJ0Br_RFnSwRx4qV", + "@timestamp": "17:05:06.186" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "eOd4wJ0Br_RFnSwRuJtq", + "@timestamp": "17:10:29.468" + } + ] + } + ], + "frontend": [ + { + "description": "Product page for National Park Foundation Explorascope (OLJCESPC7Z) returns 500 and does not show product information.", + "route": "GET /api/products/[productId]", + "deterministic": true, + "trigger_condition": "User browses product OLJCESPC7Z.", + "source_file": "src/frontend/pages/api/products/[productId]/index.ts", + "source_line": 15, + "calling_service": "frontend", + "call_pattern": "Single direct call: ProductCatalogService.getProduct(productId) → ProductCatalogGateway.getProduct(id) → gRPC GetProduct.", + "cause": "The frontend API route calls GetProduct for the requested product ID. When the flag is on and the ID is OLJCESPC7Z, the product-catalog service returns codes.Internal, and the unhandled gRPC error propagates as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Cart page returns 500 and shows an empty or broken shopping cart once OLJCESPC7Z has been added. Because POST /api/cart (add-to-cart) succeeds without calling GetProduct, the item enters the cart silently; all subsequent cart views and checkouts then fail until the cart is cleared, even for other products.", + "route": "GET /api/cart", + "deterministic": true, + "trigger_condition": "User views cart while product OLJCESPC7Z is in it.", + "source_file": "src/frontend/pages/api/cart.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all loop over cart items: items.map(({ productId }) => ProductCatalogService.getProduct(productId)). One rejection (OLJCESPC7Z) fails the entire Promise.all.", + "cause": "The GET /api/cart handler enriches each cart item by calling GetProduct. If OLJCESPC7Z is in the cart, that call returns codes.Internal, the Promise.all rejects, and the entire cart response is a 500. Note: POST /api/cart (add-to-cart) does NOT call GetProduct — it only calls CartGateway.addItem — so the item is successfully added but the subsequent cart page render fails.", + "symptom_type": "http_5xx" + }, + { + "description": "Checkout returns 500 with 'failed to get product OLJCESPC7Z' whenever OLJCESPC7Z is in the cart — not just when checking out the Explorascope itself.", + "route": "POST /api/checkout", + "deterministic": true, + "trigger_condition": "User checks out with product OLJCESPC7Z in cart.", + "source_file": "src/checkout/main.go", + "source_line": 519, + "calling_service": "checkout", + "call_pattern": "Sequential loop in prepOrderItems: for each cart item, calls cs.productCatalogSvcClient.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()}). Fails on OLJCESPC7Z and returns early.", + "cause": "The checkout service iterates cart items to look up prices. GetProduct for OLJCESPC7Z returns codes.Internal, causing prepOrderItems to return 'failed to get product #OLJCESPC7Z', which propagates through PlaceOrder back to the frontend as a 500.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section on product pages occasionally returns 500 instead of showing related products when OLJCESPC7Z is in the recommended set.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "OLJCESPC7Z is randomly selected by the recommendation service (random.sample in recommendation_server.py:107) as one of the recommended products.", + "source_file": "src/frontend/pages/api/recommendations.ts", + "source_line": 21, + "calling_service": "frontend", + "call_pattern": "Promise.all over recommended IDs: productList.slice(0, 4).map(id => ProductCatalogService.getProduct(id)). If OLJCESPC7Z is among the up-to-4 IDs, the Promise.all rejects.", + "cause": "The recommendation service itself calls ListProducts (recommendation_server.py:95), not GetProduct, so it is unaffected by the flag. But the frontend enriches the returned IDs by calling GetProduct for each one. When OLJCESPC7Z is in the random sample, the enrichment fails and the entire recommendations response is a 500.", + "symptom_type": "http_5xx" + } + ], + "traces": [ + { + "name": "Product Page Cascade", + "description": "Between 17:05:06 and 17:14:50 UTC, 8 traces show GetProduct failing for OLJCESPC7Z and cascading through the product page path.", + "cause": "Direct effect of productCatalogFailure flag — GetProduct for OLJCESPC7Z returns codes.Internal. User actions: user_add_to_cart (4), user_browse_product (4). The add-to-cart flow fetches the product page first, so the cascade is identical.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/products/[productId]/index → frontend:GET /api/products/[productId]/index → frontend:GET /api/products/{productId} → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "6ce51041034225150eddbb7e8526adbf", + "@timestamp": "17:14:50", + "user_action": "user_add_to_cart" + }, + { + "traceID": "0b56f1396e72f434f763b3d589f31295", + "@timestamp": "17:11:08", + "user_action": "user_browse_product" + }, + { + "traceID": "7191fbb09e8dfc32f243f4e459755fdc", + "@timestamp": "17:10:44", + "user_action": "user_browse_product" + }, + { + "traceID": "16098330003b5f0e2ca629015f461f07", + "@timestamp": "17:10:29", + "user_action": "user_add_to_cart" + }, + { + "traceID": "7a3ff09919c0465a7f3f83ef6bca7032", + "@timestamp": "17:09:25", + "user_action": "user_browse_product" + }, + { + "traceID": "e86718e291760196a671b79833935e49", + "@timestamp": "17:08:40", + "user_action": "user_add_to_cart" + }, + { + "traceID": "b46a5fc8ca103a6f0ce8ff4209f8b35a", + "@timestamp": "17:08:00", + "user_action": "user_browse_product" + }, + { + "traceID": "779d73e385039bb85fe3c03964f63d95", + "@timestamp": "17:05:06", + "user_action": "user_add_to_cart" + } + ] + }, + { + "name": "Recommendations Cascade", + "description": "Between 17:06:25 and 17:13:48 UTC, 11 traces show GetProduct failing for OLJCESPC7Z and cascading through the recommendations path.", + "cause": "The frontend enriches recommendation IDs by calling GetProduct for each one; when OLJCESPC7Z is among the randomly sampled IDs, the Promise.all rejects and the entire recommendations response fails.", + "call_chain": "product-catalog:GetProduct → frontend:GetProduct → frontend:executing api route /api/recommendations → frontend:GET /api/recommendations → frontend:GET /api/recommendations → frontend-proxy:router frontend egress → frontend-proxy:GET → load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: Error: Product Catalog Fail Feature Flag Enabled\"" + ], + "trace_documents": [ + { + "traceID": "d2a389794f76ff29dd893a88985c5555", + "@timestamp": "17:13:48", + "user_action": "user_get_recommendations" + }, + { + "traceID": "f4e1d6fb65d0c84b8975199f9669ada2", + "@timestamp": "17:13:43", + "user_action": "user_get_recommendations" + }, + { + "traceID": "6f9a6db62f00608e2266606039d84593", + "@timestamp": "17:13:27", + "user_action": "user_get_recommendations" + }, + { + "traceID": "5c3dcb6c1ff4363f1adeb1ea397f300a", + "@timestamp": "17:13:00", + "user_action": "user_get_recommendations" + }, + { + "traceID": "84a54753926052bdf1cedbe0caf0f912", + "@timestamp": "17:12:09", + "user_action": "user_get_recommendations" + }, + { + "traceID": "2784d242bee982579a04c52bee198064", + "@timestamp": "17:11:14", + "user_action": "user_get_recommendations" + }, + { + "traceID": "e69365872fa033f047b81f7177941658", + "@timestamp": "17:08:22", + "user_action": "user_get_recommendations" + }, + { + "traceID": "d989833385f30abc7b79aef1cad45baf", + "@timestamp": "17:08:13", + "user_action": "user_get_recommendations" + }, + { + "traceID": "ce313982297cb067dd303d5d96be1666", + "@timestamp": "17:07:53", + "user_action": "user_get_recommendations" + }, + { + "traceID": "02d50c18685a5ae18266cce739e28cf4", + "@timestamp": "17:07:45", + "user_action": "user_get_recommendations" + }, + { + "traceID": "889b09ba30950beed616b7debb860db7", + "@timestamp": "17:06:25", + "user_action": "user_get_recommendations" + } + ] + }, + { + "name": "Checkout Cascade", + "description": "Between 17:05:06 and 17:10:29 UTC, 2 traces show GetProduct failing for OLJCESPC7Z and cascading through the checkout path.", + "cause": "The checkout service calls GetProduct during prepareOrderItemsAndShippingQuoteFromCart. The extra hop through checkout:GetProduct → checkout:PlaceOrder distinguishes this from the other clusters.", + "call_chain": "product-catalog:GetProduct → checkout:GetProduct → checkout:PlaceOrder → frontend:PlaceOrder → frontend:executing api route /api/checkout → frontend:POST /api/checkout → frontend:POST /api/checkout → frontend-proxy:router frontend egress → frontend-proxy:POST → load-generator:POST", + "smoking_gun": [ + "product-catalog:GetProduct span log: feature_flag.key=productCatalogFailure, feature_flag.result.variant=on", + "product-catalog:GetProduct span event: \"Error: Product Catalog Fail Feature Flag Enabled\"", + "frontend:executing api route exception: \"13 INTERNAL: failed to prepare order: failed to get product #\\\"OLJCESPC7Z\\\"\"" + ], + "trace_documents": [ + { + "traceID": "5b6f061d4a0ad7c85f49468a620c12cc", + "@timestamp": "17:10:29", + "user_action": "user_checkout_multi" + }, + { + "traceID": "2f944b962e04693dfead03e96eb54973", + "@timestamp": "17:05:06", + "user_action": "user_checkout_multi" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-recommendationCacheFailure-on.json b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-recommendationCacheFailure-on.json new file mode 100644 index 0000000000000000000000000000000000000000..a077d226438fe1a1e5a42ef06331d75b50164fdc --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/rubrics/d6-big-recommendationCacheFailure-on.json @@ -0,0 +1,304 @@ +{ + "incident_time": "2026-04-24T17:20:00.552300+00:00", + "feature_flag": "recommendationCacheFailure", + "description": "A feature flag in the recommendation service rerouted its cache-miss path to call product-catalog `GetProduct` with an empty request proto (no product ID) instead of `ListProducts`; the catalog returned gRPC `NOT_FOUND`, which was not caught in `get_product_list`, so `ListRecommendations` failed with gRPC `UNKNOWN` and the frontend surfaced HTTP 500s on `/api/recommendations`, while the catalog-hit branch returned an empty list (because `cached_ids` was never populated) which the frontend rendered as `partial_content`.", + "mechanism": "The flag is read in at [`recommendation_server.py#L78`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L78). When the flag is enabled, on every call the code branches into the cache-failure path: with probability 0.5 (and always on the first call, since `first_run=True`), it logs `get_product_list: cache miss` and then calls `GetProduct` with `demo_pb2.Empty()` (no product ID) at [`recommendation_server.py#L84`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L84). The product-catalog server fails to look up an empty ID at [`main.go#L448`](../../opentelemetry-demo/src/product-catalog/main.go#L448) and returns `StatusCode.NOT_FOUND` with message `Product Not Found: `. The exception propagates out of `get_product_list` (lines 85-87 never execute), through `ListRecommendations` at [`recommendation_server.py#L44`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L44), and the frontend's gRPC client receives `StatusCode.UNKNOWN`, which the `/api/recommendations` route converts to HTTP 500. On the cache-hit branch (probability 0.5, never on the first call), the code returns the global `cached_ids` at [`recommendation_server.py#L92`](../../opentelemetry-demo/src/recommendation/recommendation_server.py#L92), but `cached_ids` is permanently `[]` because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86. `ListRecommendations` therefore returns zero product IDs and the frontend renders an empty recommendations section.", + "symptoms": { + "metrics": [ + { + "metric_family": "rpc_server_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "rpc_grpc_status_code": "0", + "rpc_method": "ListProducts", + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(rpc_server_duration_milliseconds_count{service_name=\"product-catalog\", rpc_method=\"ListProducts\", rpc_grpc_status_code=\"0\"}[5m])", + "description": "Product-catalog ListProducts successful call rate dropped from ~0.025-0.04/s to zero after 17:25 UTC. Normally the recommendation service calls ListProducts to fetch the product catalog, but with recommendationCacheFailure enabled, the code branches into the cache-failure path which calls GetProduct(Empty()) instead, so ListProducts is no longer invoked by the recommendation service.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "The pre-incident baseline oscillates between ~0.02-0.04. At 17:20 (the incident time), the value drops to 0.0167 and then progressively declines to zero by 17:25, never recovering. The gradual decline from 17:20-17:25 is an artifact of the 5m rate window emptying out. The last timestamp with genuine pre-incident activity is effectively 17:19 (0.025), and the collapse begins at 17:20 when successful ListProducts RPCs cease." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "root_cause", + "defining_labels": { + "service_name": "recommendation", + "span_name": "oteldemo.ProductCatalogService/ListProducts", + "status_code": "STATUS_CODE_UNSET" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived duration sample count for recommendation service's ListProducts calls. Collapsed from ~0.03/s to zero alongside the calls_total, confirming the normal ListProducts RPC path is completely abandoned.", + "onset_utc": "2026-04-24 17:20:00 UTC", + "onset_offset_seconds": 0, + "onset_reasoning": "Pre-incident values oscillate between ~0.02-0.04. At 17:20 the value drops to 0.0167, below the pre-incident minimum (~0.0208), and continues declining to zero by 17:25. This aligns exactly with the incident time. The 5m rate window smoothing causes the gradual decline rather than an instant drop." + }, + { + "type": "collapsed", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"recommendation\",span_name=\"oteldemo.ProductCatalogService/ListProducts\",status_code=\"STATUS_CODE_UNSET\"}[5m])", + "description": "Span-derived cumulative duration of recommendation service's ListProducts calls. Collapsed from ~0.1-0.2 ms/s to zero because no ListProducts spans are produced after the flag diverts to GetProduct(Empty()).", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.07-0.27. After the incident at 17:20, the signal declines steadily toward zero. 17:22 (0.054) is the last timestamp with a non-trivial value before the signal drops to ~0.032 and then zero by 17:25. The collapse clearly aligns with the incident timing." + } + ] + }, + { + "metric_family": "traces_span_metrics_duration_milliseconds", + "signal_layer": "symptom", + "defining_labels": { + "service_name": "frontend", + "span_name": "oteldemo.RecommendationService/ListRecommendations", + "status_code": "STATUS_CODE_ERROR" + }, + "variants": [ + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_sum{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived cumulative duration of frontend ListRecommendations error spans. Went from zero to ~0.1-0.6 ms/s as the gRPC UNKNOWN errors propagate from recommendation to frontend on each failed recommendation request.", + "onset_utc": "2026-04-24 17:31:00 UTC", + "onset_offset_seconds": 659, + "onset_reasoning": "The metric is a 'created' type, so we look for a significant rise after the incident time (17:20). The pre-incident baseline from 17:22-17:30 hovers around 0.05-0.12. At 17:31, the value jumps to 0.166, then sharply increases to 0.266 at 17:32 and continues climbing. 17:31 is the first timestamp showing a clear departure from the baseline level." + }, + { + "type": "created (fixed after human verification)", + "query": "rate(traces_span_metrics_duration_milliseconds_count{service_name=\"frontend\",span_name=\"oteldemo.RecommendationService/ListRecommendations\",status_code=\"STATUS_CODE_ERROR\"}[5m])", + "description": "Span-derived duration sample count for frontend ListRecommendations error spans. Went from zero to ~0.01-0.03/s, tracking the same error propagation from recommendation service to frontend.", + "onset_utc": "2026-04-24 17:22:00 UTC", + "onset_offset_seconds": 119, + "onset_reasoning": "This is a 'created' metric, meaning the series didn't exist before the incident. The first data point appears at 17:22:00 UTC, just 2 minutes after the incident time of 17:20:00. The initial values (~0.005-0.008) represent the series coming into existence, then ramping up to ~0.02-0.03 by 17:35-17:37. Since the metric type is 'created', the onset is the first timestamp where the series appears." + } + ] + }, + { + "metric_family": "db_sql_connection_closed_max_idle", + "signal_layer": "meta", + "defining_labels": { + "service_name": "product-catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(db_sql_connection_closed_max_idle_total{service_name=\"product-catalog\"}[5m])", + "description": "Rate of product-catalog DB connections closed due to max idle time. Drops ~89% because fewer DB queries means connections stay idle without cycling through the pool.", + "onset_utc": "2026-04-24 17:19:00 UTC", + "onset_offset_seconds": -60, + "onset_reasoning": "Pre-incident values oscillate between ~0.04-0.09. At 17:19 (0.054) the signal is still within normal oscillation range. Starting at 17:20 (0.0375), values drop below the pre-incident floor and continue declining to near-zero, never recovering. 17:19 is the last timestamp with clearly active pre-incident behavior." + } + ] + }, + { + "metric_family": "app_recommendations_counter", + "signal_layer": "root_cause", + "defining_labels": { + "recommendation_type": "catalog" + }, + "variants": [ + { + "type": "collapsed", + "query": "rate(app_recommendations_counter_total{recommendation_type=\"catalog\"}[5m])", + "description": "Recommendation service product-list counter flatlined to zero. With recommendationCacheFailure enabled, get_product_list either fails (cache-miss: GetProduct(Empty()) returns NOT_FOUND) or returns empty cached_ids (cache-hit: cached_ids is permanently [] because line 86 never executes), so ListRecommendations returns zero products and the counter stops incrementing.", + "onset_utc": "2026-04-24 17:21:00 UTC", + "onset_offset_seconds": 59, + "onset_reasoning": "Pre-incident pattern oscillates between ~0.10-0.21. At 17:21 the value is 0.1039, still within the normal low end. At 17:22 it drops to 0.0416, well below any pre-incident value, and continues falling to zero by 17:25. So 17:21 is the last timestamp where the pre-incident pattern is still active before the collapse." + } + ] + } + ], + "logs": [ + { + "name": "Recommendation: Cache Miss (INFO)", + "description": "At 13:20:02 ET (17:20:02 UTC), ~2.4 seconds after the incident time, the recommendation service logged its first cache miss; 7 cache-miss entries were emitted between 17:20:02 and 17:29:59 UTC, confirming the recommendationCacheFailure flag is active.", + "cause": "Emitted at recommendation_server.py:83 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=True` or `random.random() < 0.5`. The log is only reachable when the flag is on, so its presence is direct evidence of the flag being enabled. On this path the code then calls `product_catalog_stub.GetProduct(demo_pb2.Empty())` at line 84, which fails with NOT_FOUND because no product ID is provided, leaving `cached_ids` permanently empty.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache miss", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "7ueBwJ0Br_RFnSwRhrdJ", + "@timestamp": "17:20:02.999" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "9-eBwJ0Br_RFnSwR57j3", + "@timestamp": "17:20:28.863" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "YueFwJ0Br_RFnSwRQ8O3", + "@timestamp": "17:24:09.342" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "aeeFwJ0Br_RFnSwRkcTj", + "@timestamp": "17:24:28.348" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3eeIwJ0Br_RFnSwR2c_T", + "@timestamp": "17:28:03.094" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "O-eJwJ0Br_RFnSwRO9GB", + "@timestamp": "17:28:29.371" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "HeeKwJ0Br_RFnSwRm9UZ", + "@timestamp": "17:29:59.343" + } + ] + }, + { + "name": "Recommendation: Cache Hit (INFO)", + "description": "At 13:21:17 ET (17:21:17 UTC), ~76 seconds after the incident time and ~74 seconds after the first cache miss, the recommendation service logged its first cache hit; 8 cache-hit entries were emitted between 17:21:17 and 17:26:40 UTC, confirming the recommendationCacheFailure flag is still active.", + "cause": "Emitted at recommendation_server.py:91 inside the `if check_feature_flag(\"recommendationCacheFailure\")` branch when `first_run=False` and `random.random() >= 0.5`. This branch returns the global `cached_ids` without fetching from the catalog, but because every preceding cache-miss attempt fails on line 84 before reaching the assignment on line 86, `cached_ids` is always `[]`. ListRecommendations therefore returns zero product IDs on this path.", + "source": "recommendation service", + "representative_attributes": { + "body": "get_product_list: cache hit", + "severity": "INFO", + "resource.service.name": "recommendation" + }, + "log_documents": [ + { + "_index": "otel-logs-2026-04-24", + "_id": "QueCwJ0Br_RFnSwRl7vJ", + "@timestamp": "17:21:17.248" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "QOeDwJ0Br_RFnSwRqb5M", + "@timestamp": "17:22:25.443" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "beeDwJ0Br_RFnSwRvL7d", + "@timestamp": "17:22:31.001" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UueEwJ0Br_RFnSwRHr-k", + "@timestamp": "17:22:55.588" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "zueEwJ0Br_RFnSwRusDs", + "@timestamp": "17:23:34.848" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "CeeEwJ0Br_RFnSwR9cKK", + "@timestamp": "17:23:52.115" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "3-eHwJ0Br_RFnSwRU8on", + "@timestamp": "17:26:23.020" + }, + { + "_index": "otel-logs-2026-04-24", + "_id": "UOeHwJ0Br_RFnSwRjcvD", + "@timestamp": "17:26:40.515" + } + ] + } + ], + "frontend": [ + { + "description": "Recommendations section fails to load (~50% of requests, 100% on first call) because the recommendation service's cache-miss path calls GetProduct(Empty()) which returns NOT_FOUND.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on and random.random() < 0.5 (or first_run=True on the first call).", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 84, + "calling_service": "recommendation", + "call_pattern": "Single call: product_catalog_stub.GetProduct(demo_pb2.Empty()) — calls GetProduct with an Empty proto (no product ID) instead of ListProducts. The gRPC NOT_FOUND error propagates unhandled through get_product_list → ListRecommendations → frontend.", + "cause": "On cache miss, the code calls GetProduct with an empty proto. The product-catalog service receives an empty ID, fails the DB lookup (getProductFromDB at main.go:320), and returns codes.NotFound with 'Product Not Found: '. The exception propagates out of get_product_list (lines 85-87 never execute), through ListRecommendations, and the frontend receives a gRPC UNKNOWN error which becomes a 500 on GET /api/recommendations.", + "symptom_type": "http_5xx" + }, + { + "description": "Recommendations section shows no products (~50% of requests, never on first call) because cached_ids is permanently empty.", + "route": "GET /api/recommendations", + "deterministic": false, + "trigger_condition": "recommendationCacheFailure flag is on, first_run=False, and random.random() >= 0.5.", + "source_file": "src/recommendation/recommendation_server.py", + "source_line": 92, + "calling_service": "recommendation", + "call_pattern": "Returns global cached_ids (line 92) which is always [] because GetProduct(Empty()) on the cache-miss path always throws before reaching the assignment on line 86. ListRecommendations returns an empty productIds list.", + "cause": "On cache hit, the code returns cached_ids. But cached_ids is never populated — every cache-miss attempt fails on line 84 before reaching lines 86-87. So ListRecommendations returns zero product IDs, the frontend's Promise.all at recommendations.ts:20-21 resolves to an empty array, and the response is 200 with no recommendations. The user sees an empty recommendations section rather than an error.", + "symptom_type": "partial_content" + } + ], + "traces": [ + { + "name": "Recommendations NOT_FOUND Cascade", + "description": "Between 17:20:28 and 17:29:59 UTC, 6 traces show GetProduct(Empty()) returning gRPC NOT_FOUND, cascading through the recommendations path as HTTP 500s. Flag evaluation reason is 'cached' on every trace.", + "cause": "recommendationCacheFailure is enabled, causing get_product_list at recommendation_server.py:84 to call GetProduct(demo_pb2.Empty()) instead of ListProducts. The product-catalog service fails to look up an empty ID at main.go:448 and returns gRPC NOT_FOUND with message 'Product Not Found: '. The exception propagates through get_product_list -> ListRecommendations -> frontend as a gRPC UNKNOWN, which the frontend converts to HTTP 500 on GET /api/recommendations.", + "call_chain": "product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- proves GetProduct was called with no product ID (Empty() proto, recommendation_server.py:84)", + "recommendation:get_product_list span attributes: app.recommendation.cache_enabled=True, app.cache_hit=False", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=cached", + "recommendation:oteldemo.ProductCatalogService/GetProduct client span: rpc.grpc.status_code=5 (NOT_FOUND)", + "frontend:oteldemo.RecommendationService/ListRecommendations client span: rpc.grpc.status_code=2 (UNKNOWN)" + ], + "trace_documents": [ + { + "traceID": "d7d3c57eacba8cab649d1a46dc829e9b", + "@timestamp": "17:20:28" + }, + { + "traceID": "fe1a0075a66e985923a72c6b2495d359", + "@timestamp": "17:24:09" + }, + { + "traceID": "3364f571e1ced72634b2d69171c51861", + "@timestamp": "17:24:28" + }, + { + "traceID": "9df15744bdce2a351682805cfaa32c42", + "@timestamp": "17:28:03" + }, + { + "traceID": "1a6b1faf27fac81d055fc424681ae6bb", + "@timestamp": "17:28:29" + }, + { + "traceID": "6b78faedae6e21781f64e57cde8cdbeb", + "@timestamp": "17:29:59" + } + ] + }, + { + "name": "Recommendations NOT_FOUND Cascade (flagd resolve)", + "description": "At 17:20:02 UTC, 2 seconds after the incident time, 1 trace shows the same cascade as Cluster A but includes an initial flagd ResolveBoolean call with reason=static. This is the first flag evaluation in the recommendation service after the toggle, before the OpenFeature SDK cached the result.", + "cause": "Same root cause as Cluster A, but this trace captures the live flag resolution: the recommendation service calls flagd.evaluation.v1.Service/ResolveBoolean to resolve recommendationCacheFailure, receives variant=on with reason=static, then proceeds with the buggy GetProduct(Empty()) code path at recommendation_server.py:84.", + "call_chain": "flagd:resolveBoolean -> flagd:ResolveBoolean -> recommendation:ResolveBoolean -> product-catalog:GetProduct -> recommendation:get_product_list -> recommendation:ListRecommendations -> frontend:ListRecommendations -> frontend:executing api route /api/recommendations -> frontend:GET /api/recommendations -> frontend-proxy:router frontend egress -> frontend-proxy:GET -> load-generator:GET", + "smoking_gun": [ + "product-catalog:GetProduct span: app.product.id='' (empty string) and span event 'Product Not Found: ' -- same empty-ID proof as Cluster A", + "recommendation:get_product_list feature_flag.evaluation event: feature_flag.key=recommendationCacheFailure, feature_flag.result.variant=on, feature_flag.result.reason=static (live resolution from flagd)", + "flagd:flagd.evaluation.v1.Service/ResolveBoolean server span present, confirming the flag was actively resolved from flagd rather than served from the OpenFeature SDK cache" + ], + "trace_documents": [ + { + "traceID": "5c8d76868da91344b6e14c2c3ef83ee4", + "@timestamp": "17:20:02" + } + ] + } + ] + } +} diff --git a/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/test.sh b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2acf3e8ff93e39edf6410917c29900476a606fe1 --- /dev/null +++ b/tasks/d6-big-recommendationcachefailure-on-univ00-universal_ttd480m_period_same-period/tests/test.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +set +e +python /tests/check_prediction.py 2>&1 | tee /logs/verifier/log.txt +status=${PIPESTATUS[0]} +set -e + +# Preserve agent predictions even on verifier failure (Harbor deletes containers). +if [[ -f /app/report.md ]]; then + mkdir -p /logs/verifier + cp /app/report.md /logs/verifier/report.md 2>/dev/null || true +fi + +if [[ -f /app/task_meta.json ]]; then + cp /app/task_meta.json /logs/verifier/task_meta.json 2>/dev/null || true +fi + +exit $status